Usecases "let" function. "T.let(f: (T) -> R)"



I ran into “let” funtion in Kotlin standard lib:

public inline fun <T : Any, R> T.let(f: (T) -> R): R = f(this)

Could anyone share some example usecases for this funciton?


Here are few examples:

val x = nullableValue?.let { executeWithNotNull(it) } ?: defaultValue
val y = calculateExpensive().let { useSeveralTimes(it, it) }


It'd be good for that to be in the kdocs for the function.


So it kind of making the code nicer (and shorter) ?

Without this function, your examples become like:

val x = if (nullableValue != null) executeWithNotNull(nullableValue) else defaultValue

val t = calculateExpensive() val y = useSeveralTimes(t, t)