Let
Usually, we use let()
to do something only if the object is not null
:
val sometimesNull = if (Random().nextBoolean()) "not null" else null sometimesNull?.let { println("It was $it this time") }
One common gotcha here is that let()
by itself also works on nulls:
val alwaysNull = null alwaysNull.let { // No null pointer there println("It was $it this time") // Always prints null }
Don't forget the question mark, ?
, when you use let()
for null checks.
The return value of let()
is not related to the type it operates on:
val numberReturned = justAString.let { println(it) it.length }
This code will print "string"
and return Int 6
as its length.