takeIf

inline fun <T> T.takeIf(predicate: (T) -> Boolean): T?(source)

Returns this value when predicate is true, or null otherwise.

The predicate receives the original value, including null, and runs once. Its exceptions propagate and the inline predicate supports non-local returns. A null result can mean either rejection or acceptance of a null receiver.

val positive = 5.takeIf { it > 0 }

Receiver

value to test.

Return

the original receiver when accepted, or null when rejected.

Parameters

predicate

test that returns true to retain the value.

Type Parameters

T

type of the receiver, which may be nullable.

See also