scala command skips running main if class outside of singleton object -
edit: main method not called in scala script related (in particular, answer régis jean-gilles). post gives more details describe issue. , answer (by suish) give more practical demonstration explain behaviour of scala command.
content of miniscalaapp.scala
object miniscalaapp { def main(args: array[string]) = { println(s"scala version: ${scala.util.properties.scalaproporelse("version.number", "unknown")}") println(new dinosaur("tyrannotitan", 4900)) println(new dinosaur("animantarx ", 300)) } class dinosaur (name:string, weightkg: int) { override def tostring = f"$name, weight: $weightkg kg" } }
executed @ command line by:
$ scala /myproject/src/main/scala/miniscalaapp.scala
produces expected output:
scala version: 2.11.7
tyrannotitan, weight: 4900 kg
animantarx, weight: 300 kg
however, if dinosaur class placed outside of singleton object miniscalaapp scala command produces no console output, no error message.
object miniscalaapp { def main(args: array[string]) = { println(s"scala version: ${scala.util.properties.scalaproporelse("version.number", "unknown")}") println(new dinosaur("tyrannotitan", 4900)) println(new dinosaur("animantarx ", 300)) } } class dinosaur (name:string, weightkg: int) { override def tostring = f"$name, weight: $weightkg kg" }
in 2nd version, console output, code must compiled first , run miniscalaapp.class separately
$ scalac /myproject/src/main/scala/miniscalaapp.scala $ scala miniscalaapp
question: reason scala command treats code differently?
scala -help
explains all.
a file argument run scala script unless contains self-contained compilation units (classes , objects) , 1 runnable main method. in case file compiled , main method invoked. provides bridge between scripts , standard scala source.
so latter case defining object , class, run code script. in way say, same as...
scala> :paste // entering paste mode (ctrl-d finish) object miniscalaapp { def main(args: array[string]) = { println(s"scala version: ${scala.util.properties.scalaproporelse("version.number", "unknown")}") println(new dinosaur("tyrannotitan", 4900)) println(new dinosaur("animantarx ", 300)) } } class dinosaur (name:string, weightkg: int) { override def tostring = f"$name, weight: $weightkg kg" } // exiting paste mode, interpreting. defined object miniscalaapp defined class dinosaur
only defining.so need call explicitly.
miniscalaapp.main(array())
in addition that, object foo extends app
can't used if file have 1 top-lebel object.def main
is required.
Comments
Post a Comment