Scala giving me “illegal start of definition”

后端 未结 5 480
死守一世寂寞
死守一世寂寞 2020-12-13 16:48

I\'m trying to get started with Scala and cannot get out of the starting gate.

A file consisting of the line

package x

gives me

相关标签:
5条回答
  • 2020-12-13 17:29

    Since Scala 2.11.0-M7 you can use :paste -raw (fix for issue SI-5299). This option allows defining packages in the REPL:

    scala> :paste -raw
    // Entering paste mode (ctrl-D to finish)
    
    package Foo
    
    class Bar
    
    // Exiting paste mode, now interpreting.
    
    
    scala> import Foo._
    import Foo._
    
    scala> new Bar
    res1: Foo.Bar = Foo.Bar@3ee2cf81
    
    0 讨论(0)
  • 2020-12-13 17:38

    I don't get this error. How are you compiling this? And, by the way, what web site? As for REPL, it doesn't accept packages. Packages are only for compiled code.

    0 讨论(0)
  • 2020-12-13 17:42

    It looks like you're trying to declare the package membership in a Scala script (run using the scala command) or in the REPL.

    Only files defining just classes and objects which are compiled with scalac may be defined as belonging to a package.

    When you run code in a script or a REPL session, behind the scenes it is actually compiled inside a method of an object, in which scope a package declaration wouldn't be legal.

    0 讨论(0)
  • 2020-12-13 17:46

    I had the same issue when I was executing scala program eg. "Game.scala" from terminal.

    Compiling part was ok, error was shown when running the code, see below

    ☐ Wrong:

    user@pc:~$scala Game.scala
    /home/$USER/.../src/ul/org/bloxorz/Game.scala:1: error: illegal start of definition
    package ul.org.bloxorz
    
    

    Scala code should be invoked from terminal pretty much the same as Java code (you should give it a fully qualified class name and not the file name like I did in first example)

    ☑ Correct:

    user@pc:~$scala ul.org.bloxorz.Game
    
    
    0 讨论(0)
  • I had the same problem. I've resolved it by importing import packageName._ instead of declaring a worksheet in the package.

    0 讨论(0)
提交回复
热议问题