Follow the mentioned steps to understand how to create a chain of multiple lets:
- When you have to do multiple null-checks, you can obviously use nested if-else, checking null conditions, as in the following code:
if(variableA!=null){
if(variableB!=null){
if(variableC!=null){
// do something.
}
}
}
- Since we know that the let function guarantees that the block will run only when the object is not-null, we need to create a function that will perform the function of let but on three variable scenarios. Let's take a look at our function:
fun <T1: Any, T2: Any,T3:Any, R: Any> multiLet(p1: T1?, p2: T2?,p3:T3?, block: (T1, T2,T3)->R?): R? {
return if (p1 != null && p2 != null &&p3!=null) block(p1, p2,p3) else null
}
- Now we can use it as illustrated:
fun main(args: Array<String>) {
var variableA="a"
var variableB="c"
var variableC="b"
multiLet(variableA,variableB,variableC){
_,_,_->
println("Everything not null")
}
}
//Output: Everything not null
- In a similar way, it can be employed for two variable scenarios. You might be thinking how to do it in a multi-object scenario, like in the case of a list. Let's create a whenAllNotNull function, which will run the block of code only when all the elements of the list are not null:
var nonNullList=listOf("a","b","c")
nonNullList.whenAllNotNull {
println("all not null")
}
fun <T: Any, R: Any> Collection<T?>.whenAllNotNull(block: (List<T>)->R) {
if (this.all { it != null }) {
block(this.filterNotNull())
}
}
Output: all not null