Creating a chain of multiple lets in Kotlin
let
is a pretty useful function provided by Kotlin's Standard.kt
library. It is basically a scoping function that allows you declare the variable in its scope. Let's take a look at the given code:
someVariable.let{
// someVariable is present as "it"
}
However, the best thing is that it can be used to avoid null checks. Earlier, you might have used the following:
if(someVariable!=null){ // do something }
While the preceding code is good, it's not very suited for mutating properties. The alternative is to use ?.let
(someVariable.?let{}
), which ensures that the code block runs when the variable is not null. However, what if we have multiple if-not-null chains? Let's see how to deal with those cases in this recipe.
Getting ready
We will be using IntelliJ IDEA to write code. You can use any IDE that is capable of executing the Kotlin code.
How to do it…
Follow the mentioned steps to understand how to create a chain of multiple lets:
- When you have to...