Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala giving me "illegal start of definition"

Tags:

scala

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

error: illegal start of definition

Regardless of what x is and regardless of where I put the file (I had a theory that I had to place the file in a directory hierarchy to match the package definition, but no). I get the same error with the example code from the web site and with the REPL.

like image 237
Michael Lorton Avatar asked Apr 13 '10 18:04

Michael Lorton


3 Answers

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.

like image 71
Ben James Avatar answered Nov 03 '22 11:11

Ben James


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
like image 27
qtwo Avatar answered Nov 03 '22 12:11

qtwo


I had the same problem. I've resolved it by importing import packageName._ instead of declaring a worksheet in the package.

like image 3
dehasi Avatar answered Nov 03 '22 12:11

dehasi