Scala gives me an "illegal definition start"

I am trying to get started with Scala and cannot get out of the start server.

File consisting of a line

package x 

gives me

error: illegal definition start

No matter what x is, and no matter where I put the file (I had a theory that I had to put the file in a directory hierarchy so that it matches the package definition, but not). I get the same error with sample code from a website and with REPL.

+53
scala
Apr 13 '10 at 18:43
source share
5 answers

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

Only files that define only classes and objects compiled with scalac can be defined as belonging to the package.

When you run the code in a script or REPL session, behind the scenes it actually compiles inside the method of the object within which the package declaration will not be legal.

+68
Apr 13 2018-10-18T00:
source share

Since Scala 2.11.0-M7 you can use :paste -raw (fix SI-5299 problem). This option allows you to define packages in 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 
+23
Mar 02 '14 at 19:09
source share

I have the same problem. I solved this by importing import packageName._ instead of declaring the sheet in the package.

+2
May 05 '18 at 19:42
source share

I had the same problem when I was running a Scala program, for example. "Game.scala" from the terminal.

The compilation went fine, an error was shown when the code was run, see below

Rong 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 called from the terminal in much the same way as Java code (you should give it the full class name, not the file name, as I did in the first example)

☑ correct:

 user@pc:~$scala ul.org.bloxorz.Game 
0
Jun 14 '19 at 6:49
source share

I do not get this error. How do you compile this? And by the way, which website? Regarding REPL, it does not accept packets. Packages are for compiled code only.

-one
Apr 13 2018-10-22T00:
source share



All Articles