vitaly
vitaly

Reputation: 2945

Scala App initialization order

So I have a simple Scala file:

object Main extends App {
  println("Init")

  def test=println("Method")
}
Main.test
println(Main)
print("End")

and when I run it as a script I get the following output:

$ scala Main.scala
Method
Main$$anon$1$Main$@2449a2da
End

I am wondering why the println("Init") line never gets called? I would expect it to be called on initialization of Main which should happen by the time its method is called.

Upvotes: 2

Views: 700

Answers (1)

om-nom-nom
om-nom-nom

Reputation: 62835

Let's take a closer look at App trait scaladoc:

It should be noted that this trait is implemented using the DelayedInit functionality, which means that fields of the object will not have been initialized before the main method has been executed.

So you have to do something like:

object Main extends App {
  println("Init")

  def test=println("Method")
}
Main.main(Array.empty)     // here is the missing call
Main.test
println(Main)
print("End")

To get desired output:

Init
Method
Main$$anon$1$Main$@37a001ff
End% 

Upvotes: 6

Related Questions