I am learning Scala and trying to write some command line executables.
I have two version of HelloWorld, which I thought were semantically the same. HelloWorld.scala compiles and runs successfully from the command line. HelloWorld2.scala compiles but produces a runtime error.
My Question: I would think that the two would be semantically the same, so why does the second one produce a runtime error?
Here's the working example:
// HelloWorld.scala
object HelloWorld {
def main(args: Array[String]): Unit = {
println("Hello, World!")
}
}
Here's the broken example:
// HelloWorld2.scala
object HelloWorld2 {
def main
: Array[String] => Unit
= args => {
println("Hello, World!")
}
}
Here's the console output:
java.lang.NoSuchMethodException: HelloWorld2.main([Ljava.lang.String;)
at java.lang.Class.getMethod(Class.java:1778)
at scala.reflect.internal.util.ScalaClassLoader$class.run(ScalaClassLoader.scala:66)
at scala.reflect.internal.util.ScalaClassLoader$URLClassLoader.run(ScalaClassLoader.scala:101)
at scala.tools.nsc.CommonRunner$class.run(ObjectRunner.scala:22)
at scala.tools.nsc.ObjectRunner$.run(ObjectRunner.scala:39)
at scala.tools.nsc.CommonRunner$class.runAndCatch(ObjectRunner.scala:29)
at scala.tools.nsc.ObjectRunner$.runAndCatch(ObjectRunner.scala:39)
at scala.tools.nsc.MainGenericRunner.runTarget$1(MainGenericRunner.scala:65)
at scala.tools.nsc.MainGenericRunner.run$1(MainGenericRunner.scala:87)
at scala.tools.nsc.MainGenericRunner.process(MainGenericRunner.scala:98)
at scala.tools.nsc.MainGenericRunner$.main(MainGenericRunner.scala:103)
at scala.tools.nsc.MainGenericRunner.main(MainGenericRunner.scala)
HelloWorld2.mainbut you only haveHelloWorld.main. Try either changing the class name to match the file, or changing the file name to match the class (i.e. copy the code in your broken example into HelloWord.scala)mainmethod which takes anArray[String]and has return typeUnit, versus amainmethod which takes no arguments and returns a function that takes anArray[String]and has return typeUnit.