Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 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!

like image 692
Tim Stewart Avatar asked Jul 08 '11 17:07

Tim Stewart


1 Answers

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.

like image 168
Geoff Reedy Avatar answered Sep 20 '22 18:09

Geoff Reedy