Discuss the difference between 'def', 'val', and 'lazy val' in terms of initialization.
Instruction: Explain with examples how 'def', 'val', and 'lazy val' differ in their initialization and usage within Scala applications.
Updated
A val evaluates its initializer when execution reaches the declaration and then keeps that binding. A def evaluates its body when called. A lazy val delays initialization until first access and caches the successfully initialized result.
class Evaluation {
var calls = 0
private def next(): Int = { calls += 1; calls }
val eager: Int = next()
def repeated: Int = next()
lazy val delayed: Int = next()
}
@main def evaluationExample(): Unit = {
val e = new Evaluation
assert(e.calls == 1 && e.eager == 1)
assert(e.repeated == 2 && e.repeated == 3)
assert(e.delayed == 4 && e.delayed == 4)
assert(e.calls == 4)
}
Here the eager field initializes during each Evaluation object's construction, not once at application startup. A local val initializes when its block executes. A def can return the same value on every call if its computation does so; repeated clock reads, for example, need not differ. Definitions and evaluation
Choose according to semantics: val for an immediately available value, def for an operation or fresh computation, and lazy val for deferred shared initialization. A failed lazy initializer is not a successfully cached value and can be retried. Lazy initialization can introduce synchronization and initialization-cycle concerns; it is not a universal optimization. A stable binding also does not make the referenced object's contents immutable. Scala 3 lazy initialization