Arnab Das Arnab Das - 1 year ago 85
Scala Question

Does Scala lazy val actually evaluates the expression to get the final type during assignment

I'm completely new to Scala. I'm confused at the behavior of

lazy val
in REPL.

scala> lazy val a = {println("Hello, World!!!"); 5}
a: Int = <lazy>

scala> a
Hello, World!!!
res0: Int = 5

I can see that, in the REPL, the type of the
lazy val
has been assigned correctly, immediately after the declaration.

Now, my question, is Scala interpreter actually evaluates the expression lazily, or just evaluates, but does not store the evaluated resultant value to the intended variable.

Thanks in advance.

Answer Source

Short answer: no.

Longer answer: the type inference algorithm does not require to run the code, it only has to analyze the abstract syntax tree (the structured representation of your code produced by the parser) to infer the type and lazy vals make no exception.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download