Lazy — Memoized Computations
Evaluating expensive synchronous operations (such as large config parsing or regex compilation)
eagerly at startup increases initialization time, while plain thunks (() => A) recompute on every
call.
Lazy<A> defers execution until first accessed via .get() and caches the result for all
subsequent evaluations:
Lazy defers the execution of the computation until the exact moment the value is first requested.
Once evaluated, it caches the result, serving it instantly from memory for all subsequent requests
without ever executing the underlying operation again.
Creating and Evaluating
Section titled “Creating and Evaluating”We lift synchronous thunks into the Lazy context using its core constructor:
To force the evaluation of the thunk and extract the cached result, we use Lazy.evaluate:
Transforming and Sequencing
Section titled “Transforming and Sequencing”You can map over and sequence lazy computations point-free without triggering their evaluation.
Transforming results with map
Section titled “Transforming results with map”map describes how the deferred value should be transformed once it is eventually requested,
returning a new Lazy container:
Sequencing dependencies with chain
Section titled “Sequencing dependencies with chain”When a transformation itself returns a Lazy container, we use chain to flatten the nested
context:
Peeking with tap
Section titled “Peeking with tap”Lazy.tap executes a side-effectful callback when the lazy container is evaluated for the first
time, passing the computed value through unchanged:
Problems it solves
Section titled “Problems it solves”- Deferring expensive startup computations: Compiling large regular expression suites, parsing
extensive localization dictionaries, or validating JSON schemas at application startup degrades
boot performance.
Lazypostpones execution until a code path explicitly calls for the value, skipping the work entirely if that branch is not reached. - Request-scoped derivation memoization: Within an HTTP request handler or calculation pipeline,
multiple helper functions may require the same derived data (such as a decoded auth token payload,
a compiled discount table, or a permission matrix).
Lazycomputes the value on the first access and caches the outcome for all subsequent steps within the request lifecycle. - Safe deferred dependency pipelines: In modular services, constructing values that depend on
other computed settings can trigger eager initialization ordering issues.
Lazyallows transformation pipelines to be assembled point-free and evaluated only when downstream consumers require them.