Take the following example which uses safe call operator (?.):
class Sample {
class A(
val sampleB: B? = B()
)
class B(
val sampleC: C = C()
)
class C(
val sampleInt: Int = 1
)
fun test() {
val intInC: Int? = A().sampleB?.sampleC?.sampleInt
}
}
I understand that we need a safe call operator on sampleB. But why do we need the safe call operator on sampleC. If I remove that operator, it does not compile.
Based on my understanding of the operator, if sampleB were null, the line returns null. And if sampleB is not null, we can be sure that sampleC is not null, based on its type. But why does Kotlin force safe call operator on sampleC ?
The basic difference between the Safe call and Null check is that we use Null checks (!!) only when we are confident that the property can't have a null value. And if we are not sure that the value of the property is null or not then we prefer to use Safe calls(?.).
This is a binary expression that returns the first operand when the expression value is True and it returns the second operand when the expression value is False. Generally, the Elvis operator is denoted using "?:", the syntax looks like − First operand ?: Second operand.
A safe call is denoted by the operator( ? ) — It is used in case you want to check the null condition and if the expression is null then by default it will return null or else it will return the value that is instructed.
A().sampleB?.sampleC?.sampleInt
parses as
((A().sampleB)?.sampleC)?.sampleInt
The types are
A(): A
A().sampleB: B?
(A().sampleB)?.sampleC: C?
((A().sampleB)?.sampleC)?.sampleInt: Int?
Because the type before sampleC
is a B?
, the ?.
is required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With