slouc slouc - 1 month ago 12
Scala Question

Scala recursive val behaviour

What do you think prints out?

val foo: String = "foo" + foo
println(foo)

val foo2: Int = 3 + foo2
println(foo2)


Answer:

foonull
3


Why? Is there a part in specification that describes/explains this? (I mean foo being
null
on the right hand side of first assignment and the mechanism not having the same behaviour in the second example)

Answer

Yes, see the SLS Section 4.2.

foo is a String which is a reference type. It has a default value of null. foo2 is an Int which has a default value of 0.

In both cases, you are referring to a val which has not been initialized, so the default value is used.