Home > database >  Order of instantiation between Val, def, lazy val in Scala
Order of instantiation between Val, def, lazy val in Scala

Time:10-11

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:

  1. val v gets evaluated on its initalization and prints v.
  2. next, var s gets initialized and is assigned d which evaluates def d and thus prints d.
  3. then, 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.
  4. assigning v to s prints nothing because the value (3) was stored during the initializaton of v (-> step 1).
  5. re-assigning 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).
  6. re-assigning 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.)

  • Related