Arnab Das Arnab Das - 4 months ago 28
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.


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.