Sunday, 21 June 2015

Coffee With Scala

What is difference between def and val ?
-- Def evaluate every time we access them but val only evaluate when object referenced first time.

Details on

  1. val
  2. lazy val
  3. def

Following example is best way to understand above three.

scala> class X { val x = { Thread.sleep(2000); 15 } }
defined class X

scala> class Y { lazy val y = { Thread.sleep(2000); 13 } }
defined class Y

scala> new X
res5: X = X@262505b7 // we have to wait two seconds to the result

scala> new Y
res6: Y = Y@1555bd22 // this appears immediately

No comments:

Post a Comment