Question

I just installed the Eclipse Scala IDE and imported some existing projects. However, when I want to run the classes (that contain a main def) via right click -> Run, I only get 'Run configurations...'. How can I run these Scala classes?

(I already checked that the 'Scala Nature' is added.)

Was it helpful?

Solution

You need to run an object not a class as noted by urban_racoons. so you can run either:

object MyApp{
  def main(args: Array[String]): Unit = {
    println("Hello World")
  }
}

or

object MyApp extends App {   
  println("Hello World")   
}

Scala can not run a class because the main method needs to be static. Which can only be created behind the scenes by the compiler from a singleton object in Scala. Create the object and "run as a Scala application" should appear in the "run" context sub menu as long as you have the Scala perspective open.

You can still access the programme's arguments using the App trait as in

object MyApp extends App {   
  println("The programme arguments are:")
  args.foreach(println)
  // the above is just shorthand for 
  // args.foreach(ar => println(ar))  
}

It should also be noted that App is a trait. So it can be mixed in with other traits and any class, which makes it handy for rapid prototyping.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top