WeakLazy

class WeakLazy<T : Any>(initializer: () -> T)

A lazily computed value cached through a WeakRef, so the cached instance can be garbage collected and recomputed later.

Reading value runs the initializer on first access and whenever the previously cached instance has been collected, so the initializer may run more than once and must be pure enough to tolerate that. Between collections, reads return the same instance. This makes WeakLazy a fit for expensive-to-build but reconstructible objects such as parsed resources, caches, or renderers.

On targets where WeakRef.isWeakSupported is false (Kotlin/Wasm, and JS runtimes without ES2021 WeakRef) the cached instance is held strongly and is never collected, so after the first read this behaves like a plain lazy, although refresh and clear still replace or drop the cache.

This class is not thread-safe. Concurrent reads may each run the initializer and observe different instances; confine an instance to one thread or add external synchronization.

val table = weakLazy { loadHyphenationTable() }
table.value.hyphenate(word) // recomputed transparently if collected

Parameters

initializer

computes the value; invoked on first read and after each collection, refresh, or clear.

Constructors

Link copied to clipboard
constructor(initializer: () -> T)

Properties

Link copied to clipboard
val value: T

The current value, computing and caching it when absent.

Functions

Link copied to clipboard
fun clear()

Drops the cached instance without computing a replacement.

Link copied to clipboard
fun peek(): T?

Returns the currently cached instance, or null, without computing.

Link copied to clipboard
fun refresh(): T

Discards any cached instance, recomputes eagerly, and returns the fresh value.