Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala values initialization

Tags:

scala

Why in this example, no error is thrown and b ends up holding default value?

scala> val b = a; val a = 5
b: Int = 0
a: Int = 5
like image 912
Rogach Avatar asked Jan 18 '12 09:01

Rogach


1 Answers

When you do this in the REPL, you are effectively doing:

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

b and a are assigned to in order, so at the time when you're assigning b, there is a field a, but it hasn't yet been assigned to, so it has the default value of 0. In Java, you can't do this because you can't reference a field before it is defined. I believe you can do this in Scala to allow lazy initialisation.

You can see this 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 have the correct values assigned if you make a 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 a lazy val:

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

scala> new Foobar().b
res5: Int = 5
like image 81
Matthew Farwell Avatar answered Oct 13 '22 20:10

Matthew Farwell