Understanding DelayedInit

Viewed 3443

I'm looking at DelayedInit in Scala in Depth ...

Comments are my understanding of the code.

The following trait accepts a single argument, which is non-strictly evaluated (due to =>), and returns Unit. Its behavior is similar to that of a constructor.

trait DelayedInit {
  def delayedInit(x: => Unit): Unit
}

As I understand App, this trait has a var x that equals a function of 0-arity (no arguments). x gets assigned based on a call to the delayedInit method.

Then, main will call apply '_()' on x if it has a Some(Function0[Unit]) type. If x is None, then nothing will happen.

trait App extends DelayedInit {
  var x: Option[Function0[Unit]] = None
  override def delayedInit(cons: => Unit) {
    x = Some(() => cons)
  }
  def main(args: Array[String]): Unit =
    x.foreach(_())
}

Then, I went to REPL per the book's examples:

scala> val x = new App { println("Now I'm initialized") }
x: java.lang.Object with App = $anon$1@2013b9fb

I saw that the output of ...

scala> x.main(Array())

was nothing.

Should the construction of an App instance result in calling delayedInit so that x.main(Array()) returns the constructor-like behavior? Or, more concretely, should Now I'm initialized be expected to have printed out?

1 Answers
Related