Why does the same scala code work fine on the command line and not in Intellij?

Below is a very simple code scala

( 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 on the command line, it's ok:

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

      

But when you run the command with the "Scala console" command, Intellij

it throws 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!"))
^

      

Screenshot Like:
enter image description here Could anyone please give some insight on this issue?

+3


source to share


2 answers


You define a value and call a function right inside a file (assembly block), which is not allowed in Scala. It worked in the REPL because it just implicitly wraps it in 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 will also not work with the usual scalac

one if you are looking for a clean check.



Solution: just use App

which will automatically generate a method main

so you can run the code:

 object MyApp extends App {
   val up = new Upper
   println(up.upper("Hello World!"))
 }

      

+4


source


I think this is a problem for scala scripts in intellij, one way to run these scripts is a little more complicated. From my point of view, create and an object that extends and the app builds a scala app, not a scala script

First remove the make element in the config:

enter image description here

Then start scala console

enter image description here



Next, you have to select the code and send to the console

enter image description here

and finally you can see the result in the console

enter image description here

I hope this works, for running your script code without creation and application

+3


source







All Articles