let in kotlin help me avoid some if(null?) doSomething.
But I have a problem.
A is the field of the object, And B is the field of Object A. they can be nullbale.
They in code like this.
class Obj {
var a : A?
}
class A {
var b : B?
}
I knew I can do it by double let:
A?.let {
it.B.let {
// a must nonnull
}
}
A?.B?.let {
// how to use A ,without null check again?
}
There are extension functions out there to achieve what you're looking for, you can find them in this thread https://discuss.kotlinlang.org/t/kotlin-null-check-for-multiple-nullable-vars/1946
But honestly, you're probably better of just using a basic if check here, if the variable is mutable you can assign it to a
val
first.Edit: If you still really want to use let though, for this case you could create a pair and use
takeIf
However the compiler won't smartcast the values as non-null, so you will still have to perform a non-null (!!) assertion on them.
By default Kotlin avoids
null
values and forNull Safety
it provides:1) Safe Call Operator( ?. )
2) Not-Null Assertion( !! )
3) Elvis Opeartor( ?: )
4) Safe Call with let ( ?.let{...} )
Safe Call Operator( ?. ):Checks if the property is not null before performing any operations.
Not-Null Assertion( !! ) : Explicitly tells the compiler that the property is not null and if it’s null, please throw a null pointer exception (NPE)
Elvis Opeartor( ?: ): It's like ternary operator in java. If property is not null then left expression is returned otherwise right.
Safe Call with let ( ?.let{...} ): It will execute the let block only if property is not null
Output (With Not Null Value inside property)
Safe Call operator: 5
Safe Call wih let operator: 5
Elvis operator : 5
Not Null Assertion Operator : 5
Output (With Null Value inside property)(val name: String? = null)
Here, safe call with let is not executed!! And Not-Null assertion operator throws null pointer exception.
Your problem can use not-null assertion operator:
You could implement it like a Swift guard with an elvis operator
?:
Here
a
andb
are non-nullable references to the data you hold in In this case you'd just return from your function.