fold

inline fun <T, R> T.fold(predicate: T.() -> Boolean, falsy: T.() -> R, truthy: T.() -> R): R

Syntax-sugar for a lambda that folds a receiver type T into type R.

This should primarily be used when chaining.

val result: String = "Hello"

// Before:
val a = 7
val b = if (a % 2 == 0) null else a
val c = b?.toString().orEmpty()

// After:
7.fold(
predicate = { this % 2 == 0 },
falsy = { null },
truthy = { this }
).toString().orEmpty()

Parameters

T

The type of the receiver.

R

The type of the return value.

predicate

The predicate to evaluate on the receiver.

falsy

The lambda to call if the predicate returns false.

truthy

The lambda to call if the predicate returns true.

See also