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?
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:
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.
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