WeakRef

expect class WeakRef<T : Any>(referred: T)(source)

A weak reference to T: holds its referent without keeping it alive.

get returns the referent, or null once it has been collected or after clear. Check isWeakSupported before leaning on collection for correctness.

Platform behaviour:

  • JVM, Android, Apple/Native: the platform's own weak reference.

  • JS: the ES2021 WeakRef global. On an older runtime, and for referents backed by JS primitives (String, boxed numbers) that WeakRef will not accept, the referent is held strongly instead.

This is the engine's only expect/actual. WeakMap and WeakSet need it and there is no multiplatform weak reference in the standard library.

Constructors

Link copied to clipboard
expect constructor(referred: T)

Types

Link copied to clipboard
expect object Companion

Functions

Link copied to clipboard
expect fun clear()

Drops the reference, so get returns null from here on. Calling it twice is fine.

Link copied to clipboard
expect fun get(): T?

The referent, or null once collected or cleared.