Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding DelayedInit

Tags:

scala

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?

like image 217
Kevin Meredith Avatar asked Dec 18 '13 05:12

Kevin Meredith


1 Answers

I'm guessing you defined your own DelayedInit trait at the same file as App. If you did this, delete it, DelayedInit is a trait inside the scala package.

I just got the code from the book and pasted right into an Eclipse worksheet and it just works.

EDIT

What happens is that the code inside delayedInit gets called just before the constructor at the anonymous App object you are creating with new App { println("Now I'm initialized") }. You can see it at this screenshot:

Worksheet showing the code being executed

If you decide to remove this line:

x = Some(() => cons)

You will see that Now I'm initialized is never printed. Because the constructor code for the anonymous App object you are creating is given to the delayedInit method but is never run anywhere, so the App's object constructor is never run.

like image 200
Maurício Linhares Avatar answered Nov 09 '22 18:11

Maurício Linhares