Kotlin: Don’t just use LET for null check

Last updated 2 years ago by Elye Project


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 process(@Nullable String str) { if (str != null) { boolean var4 = false; /*Do something*/ } }

It introduce a variable. If you process function is used lots of time, it is doing something extra without any benefits.

Read full Article