Arnab Das
Arnab Das

Reputation: 3738

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 a 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.

Upvotes: 0

Views: 74

Answers (2)

stefanobaghino
stefanobaghino

Reputation: 12804

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.

Upvotes: 4

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369594

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.

It's easy to see that it must be the first one, since if it were the second one, Hello, World!!! would be printed twice.

Upvotes: 3

Related Questions