开发者

In Scala static value initialization does not appear to be happening before the main method is called

开发者 https://www.devze.com 2023-03-19 09:58 出处:网络
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:

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 tho开发者_运维问答ught 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.


Try

lazy val x = "Hello World"

That should give you the results you're expecting.


You are not support to have a main method on an object extending App. If you do override it, you'd better understand how, exactly, DelayedInit works. In particular, objects extending App do not have static initialization -- that's the whole point of App.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号