Kotlin: Don’t just use LET for null check

With the introduction of null safety in Kotlin, everybody now know this special standard function let{...}.

The example given in null safety document is as below

val listWithNulls: List<String?> = listOf(“Kotlin”, null)
for (item in listWithNulls) {
item?.let { println(it) } // prints Kotlin and ignores null
}

Hence let is inevitably being understood that it is the replacement of null check e.g. if (variable != null). Illustrated further below

// Conventional approach
if (variable != null) { /*Do something*/ }
// Seemingly Kotlin approach
variable?.let { /*Do something*/ }

While, this is permissible, it is not right to use let{...} all the time.

When not to use LET

Recommendation 1.1: When just checking null for an immutable variable, don’t use LET.

Imagine if you have a function that receive a nullable String as below. It may seems seems nice to do something as below.

// NOT RECOMMENDED
fun process(str: String?) {
str?.let { /*Do something*/ }
}

But if you check the decompiled Java code, it is

public final void…

--

--