Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - chaining of safe call operator. unnecessary operator calls

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 ?

like image 309
Nishanth Avatar asked Nov 18 '17 03:11

Nishanth


People also ask

What is the difference between safe calls (? And null check?

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(?.).

What does ?: Mean in Kotlin?

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.

What is safe call operator in Kotlin?

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.


1 Answers

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.

like image 85
ephemient Avatar answered Sep 18 '22 11:09

ephemient