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
}
CodePudding user response:
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.- next,
var s
gets initialized and is assignedd
which evaluatesdef d
and thus prints d. - then,
lazy val l
is assigned tos
- this is the first timel
gets used, so this is when it is evaluated and prints l. - assigning
v
tos
prints nothing because the value (3) was stored during the initializaton ofv
(-> step 1). - re-assigning
l
tos
prints nothing because the value (5) was stored during the initializaton ofl
(which happend the first time it was used in step 3). - re-assigning
d
tos
prints d becaused
is adef
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
.)