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


#1

Hi,

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?


#2

Here are few examples:

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


#3

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


#4

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)