castOrElse

inline fun <T> Any?.castOrElse(default: () -> T): T

Casts Any to a type T or returns a default value.

// Chained function call alternative to:
this as? T ?: default // Default value
this as? T ?: return@scope // Early escape
this as? T ?: run { ... } // If-null block
this as? T ?: throw IllegalStateException("Custom Exception")

Return

The cast value of type T or the result of the default lambda if the cast fails.

Parameters

default

A lambda that provides a default value of type T.

See also