You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
objectOne {
vala= b -1valb= a +1valanswer= a + b
}
Trick question! This code doesn't work. Here a and b are defined in terms of each other which leads to a circular dependency that can't be resolved.
problem
I think the reason because this code doesn't work is actually two folds.
Circular declaration itself is not forbidden with Scala. It just requires a type annotation on b as val b: Int = a + 1.
The reason it doesn't "work", as in it will actually return incorrect value is because val a = b - 1 is referencing b before it is initialized, which seems to be treated as 0. Making answer into (0 - 1) + (0 - 1 + 1), which is -1.
scala>objectOne {
|vala= b -1|valb:Int= a +1||valanswer= a + b
| }
<console>:12:warning: Reference to uninitialized value b
vala= b -1
^
defined objectOne
scala>One.answer
res1:Int=-1
expectation
If we want to expose the readers to val initialization order issue, it might be worth changing the exercise to:
objectOne {
vala= b -1valb=10valanswer= a + b
}
and note that fact that without -Xfatal-warnings one could end up with incorrect answer?
The text was updated successfully, but these errors were encountered:
https://github.com/underscoreio/creative-scala/blob/develop/src/pages/programs/names.md#exercises--
original
problem
I think the reason because this code doesn't work is actually two folds.
b
asval b: Int = a + 1
.val a = b - 1
is referencingb
before it is initialized, which seems to be treated as0
. Makinganswer
into(0 - 1) + (0 - 1 + 1)
, which is-1
.expectation
If we want to expose the readers to
val
initialization order issue, it might be worth changing the exercise to:and note that fact that without
-Xfatal-warnings
one could end up with incorrect answer?The text was updated successfully, but these errors were encountered: