🔴 Scala Beginner

What is the difference between def, val, and lazy val for methods/values?

Answer

These three define different evaluation strategies. def: evaluated every time it is called. def random = math.random() — each call returns a different value. Used for methods and call-by-name semantics. val: evaluated once when the enclosing class/object is initialized. val fixed = math.random() — same value every time, computed at initialization. lazy val: evaluated once on first access, then cached. lazy val onDemand = expensiveComputation() — computed only if and when first accessed. Performance: def recomputes each access (could be desired for side effects or current state). val uses memory but avoids recomputation. lazy val is thread-safe (uses double-checked locking in the JVM) and avoids initialization-order issues. Prefer val for pure values, def for parameterized or stateful computations, lazy val for expensive one-time computations.