nullfold

inline fun <In, Out> In.nullfold(none: (NullPointerException) -> Out, some: (In & Any) -> Out): Out

Syntax-sugar for a lambda folds a nullable receiver type into type Out.

Looks dumb, but weirdly useful in the right context.

val result: String? = null

// Before:
result?.length ?: 0

// Before:
when (result) {
null -> 0
else -> result.length
}

// After:
result.nullfold(none = { 0 }, some = { it.length })

Return

The result of the lambda passed to some or none.

Parameters

In

The type of the receiver.

Out

The type of the return value.

none

The lambda to call if the receiver is null.

some

The lambda to call if the receiver is not null.