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
vinayagasundar
04/26/2020, 2:42 AM
It's because your not adding any null check to the
also
method. Change like this
node?.also
a
Animesh Sahu
04/26/2020, 6:46 AM
@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
vinayagasundar
04/26/2020, 6:51 AM
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.
vinayagasundar
04/26/2020, 6:52 AM
This is called
short-circuit
evaluation
a
Animesh Sahu
04/26/2020, 6:54 AM
+1
g
Gopal S Akshintala
04/26/2020, 9:30 AM
I see thanks @vinayagasundar, seems the compiler cannot connect two lines while smart casting