My Scala version:
Scala code runner version 2.9.0.1 -- Copyright 2002-2011, LAMP/EPFL
Given this code in a file named Static.scala:
object Main extends App {
val x: String = "Hello, World!"
override def main(args: Array[String]): Unit = {
println(x)
}
}
When I run:
scalac Static.scala && scala Main
I see:
null
instead of:
Hello, World!
I thought that x was a static because it was defined in an object, and that it would be initialized prior to the main method being called.
What am I doing wrong? Thanks!
This happens because of how you used the App trait. The App trait uses the DelayedInit feature which changes how the class body (including field initialization) is executed. The App trait includes a main method which executes the class body after binding the args field to the arguments to the program. Since you have overridden main this initialization is not happening. You should not provide a main method when using the App trait. You should either put the application code directly in the class body or not inherit from the App trait.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With