nullableOf

inline suspend fun <T> nullableOf(block: () -> T): T?

Suspend runner that catches and normalizes most thrown exceptions into a null value.

  • Will NOT catch CancellationException if the coroutine is no longer active!

  • Does NOT catch Error subclasses. Errors should be fatal.

val a: String? = nullableOf { throw Exception() } // == null
val b: String? = nullableOf { "Hello, World!" } // == "Hello, World!"

Shorthand for try { block() } catch (_: Exception) { null } with an ensureActive guard on CancellationException.

Return

The result of block, or null if an Exception was thrown.

Parameters

T

The return type of block.

block

The protected try-block which may throw an Exception.

See also

Throws

Always rethrown — Error subclasses are not caught.

CancellationException

If the coroutine has been cancelled.