Why do we use let{} as null checking in Kotlin?

Why do we use exactly let{} as null checking in Kotlin?

Aren't other scope functions suitable for this? They do pretty much the same thing.

Upvotes: 0

Views: 116

Answers (1)

Tenfour04
Tenfour04

Reputation: 93609

It's an idiom. When everybody usually does things in basically the same way, it makes code easier to read and follow because your brain has to do less work to comprehend it. You can immediately grasp what's happening when you see an idiomatic pattern without having to reason through all its logic.

The reason let is the natural choice out of the scope functions, I think:

  1. You usually only need to do this kind of null-check so you can do something with the non-null object. If you just wanted to call something on the non-null object, you could have just used ?.doWhatever() instead of ?.run { doWhatever() }. This rules out run and apply for readability reasons. run { doSomething(this) } is considered a little more awkward than let { doSomething(it) }.

  2. Not always, but often, you want to do something with the return value of whatever function you're passing the non-null object to. This rules out also.

And with can't be used with ?. safe invoke since it is a top level function with no receiver.

Those other functions run, apply, and also could be the best choice under some circumstances, but in most cases they have no readability advantage over let and so you may as well use the idiomatic choice.

Upvotes: 3

Related Questions