Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the same scala code work OK in command line while not in Intellij?

The following is a very simple scala code (upper.scala):

/**
 * Created on 7/6/2015.
 */
class Upper {
  def upper(strings: String*): Seq[String] = {
    strings.map((s: String) => s.toUpperCase())
  }
}

val up = new Upper
println(up.upper("Hello World!"))

Execute it in command line, it is OK:

[root@Fedora ~]# scala upper.scala
ArrayBuffer(HELLO WORLD!)

But when executing it with Run 'Scala console' command in Intellij, it prompts the following error:

Error:(10, 1) expected class or object definition
val up = new Upper
^
Error:(11, 1) expected class or object definition
println(up.upper("Hello World!"))
^

The screen shot likes this:
enter image description here Could anyone give some clue on this issue?

like image 818
Nan Xiao Avatar asked Feb 18 '26 23:02

Nan Xiao


2 Answers

You're defining a value and calling for function right inside file (build unit), which is not allowed in Scala. It worked in REPL because it just implicitly wraps it into some default object, like:

object $iw {
  class Upper {
    def upper(strings: String*): Seq[String] = {
      strings.map((s: String) => s.toUpperCase())
    }
  }

  val up = new Upper
  println(up.upper("Hello World!"))
}

Your approach also won't work with plain scalac if you're looking for clean check.

Solution: just use App trait, which will generate main method automatically so you can run the code:

 object MyApp extends App {
   val up = new Upper
   println(up.upper("Hello World!"))
 }
like image 69
dk14 Avatar answered Feb 20 '26 13:02

dk14


I think that this is an issue for scala scripts in intellij, One way of running this scripts is a little bit tricky. From my point of view making and object that extends and app is building an scala application not a scala script

First remove the make item, in the configuration:

enter image description here

Then run the scala console

enter image description here

Next you must select the code and send to console

enter image description here

and finally, you can see the result in the console

enter image description here

I hope that this works, for running your code script, without making and App

like image 25
anquegi Avatar answered Feb 20 '26 13:02

anquegi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!