I am learning Scala basics. I just came across the lazy val concept. I have following code snippets which work without errors/warnings
Case 1
lazy val a = 10 + b
lazy val b = 5
println(a)
Case 2
lazy val a = 10 + b
val b = 5
println(a)
Case 3
val a = 10 + b
lazy val b = 5
println(a)
I understand how case 1 & 2 work. But I don't understand how the code in case 3 is working without error/warning. How is Scala able to evaluate the value of a when b is not yet defined?
EDIT
I am not running this code in Scala REPL. I have saved the code in case 3 in file called lazyVal.scala. I am executing it using scala lazyVal.scala. I think scala interprets the code in the file.
If I change the code in lazyVal.scala to
val a = 10 + b
val b = 5
println(a)
And execute it using scala lazyVal.scala I do get warning
/Users/varun.risbud/scalaRepo/src/Chapter1/lazyVal.scala:1: warning: Reference to uninitialized value b
val a = 10 + b
^
one warning found
10
Also If I change the code to create object and extend App it works
object lazyVal extends App {
val a = 10 + b
lazy val b = 5
println(a)
}
ā Chapter1 scalac lazyVal.scala
ā Chapter1 scala lazyVal
15
My scala version is 2.12.1 if that makes any difference.