read

open override fun read(): T?(source)

Attempts to read the value held by this reference.

If the value was garbage-collected, which may happen at any time, this accessor returns null.

One should not assume any additional behavior. In particular, the value may continue to be returned long after it has become unreachable from anywhere else in the program, or disappear sooner than one expected.

Native limitations

On Kotlin Native, values can only be freed by the GC in a different frame than the one they were created in. This means that if you call read within the body of a function, the weak reference cannot be cleared anymore until the end of the function.

Be careful of this limitation when using weak references inside a single expensive function.

To learn more, follow KT-79985.

See also

Test if the reference has been cleared.