nullable

inline fun <T> nullable(block: () -> T): T?

Runner that catches and normalizes all thrown exceptions into a null value.

  • Will catch CancellationException! In a suspend context, use nullableOf instead.

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

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

Shorthand for try { block() } catch (_: Exception) { null }.

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.