Why DOESN’T Kotlin smart cast work here? ```fun SL...
# announcements
g
Why DOESN’T Kotlin smart cast work here?
Copy code
fun SLLNode?.sumListWith(node: SLLNode?, carry: Int = 0): SLLNode? =
    when {
        this == null && node == null -> if (carry == 0) null else SLLNode(carry)
        this == null -> node.also { it!!.value += carry } // Smart cast doesn't work here.
        node == null -> this.also { value += carry } // Works here.
        else -> {
            ...
        }
    }
v
It's because your not adding any null check to the
also
method. Change like this
node?.also
a
@vinayagasundar he meant if (this==null&&node==null) is false and (this==null) is true then node must be not-null. So he asked why would he need to use null checks 😃
v
Hmm, for that we need to understand how the
&&
operator works. if the first condition fails ie.
this == null
. It won't evaluated the seconds condition
node==null
. because we already know the final result will be
false
anyway.
This is called
short-circuit
evaluation
a
+1
g
I see thanks @vinayagasundar, seems the compiler cannot connect two lines while smart casting
👍 1