Scala value initialization

Why does this not cause an error in this example, and does b end with a default value?

scala> val b = a; val a = 5
b: Int = 0
a: Int = 5
+5
source share
1 answer

When you do this in REPL, you effectively do:

class Foobar { val b = a; val a = 5 }

b and a are assigned in order, so while you assign b, there is a field a, but it is not assigned yet, so it has a default value of 0. In Java, you cannot do this because you cannot reference on the field until it is determined. I believe that you can do this in Scala to allow lazy initialization.

This can be done more clearly if you use the following code:

scala> class Foobar {
  println("a=" + a)
  val b = a
  println("a=" + a)
  val a = 5
  println("a=" + a)
}
defined class Foobar

scala> new Foobar().b
a=0
a=0
a=5
res6: Int = 0

You can assign the correct values ​​if you create a method:

class Foobar { val b = a; def a = 5 }
defined class Foobar
scala> new Foobar().b
res2: Int = 5

or you can make b lazy val:

scala> class Foobar { lazy val b = a; val a = 5 }
defined class Foobar

scala> new Foobar().b
res5: Int = 5
+11
source

All Articles