Reputation: 3
Can anybody walk me through how this can out vdld pleeease?
def deflazyval() : Unit = {
lazy val l : Int ={print("l") ; 5}
def d : Int ={print("d") ; 7}
val v : Int ={print("v") ; 3}
var s : Int = d
s += l
s += v
s += l
s += d
}
Upvotes: 0
Views: 68
Reputation: 1258
def
gets re-evaluated every time it is used, lazy val
gets evaluated the first time is used, val
gets evaluated on its initialization. So:
val v
gets evaluated on its initalization and prints v.var s
gets initialized and is assigned d
which evaluates def d
and thus prints d.lazy val l
is assigned to s
- this is the first time l
gets used, so this is when it is evaluated and prints l.v
to s
prints nothing because the value (3) was stored during the initializaton of v
(-> step 1).l
to s
prints nothing because the value (5) was stored during the initializaton of l
(which happend the first time it was used in step 3).d
to s
prints d because d
is a def
and thus gets re-evaluated every time it is called.(N.B.: since you are using +=
, it would be more precise to write "s + x
is assigned to s
" where I just wrote "x
is assigned to s
", but for the question at hand (why things get printed), it does not matter whether you do v += x
or v = x
.)
Upvotes: 4