Shouldn't the safe call operator (?.) stop evaluat...
# getting-started
l
Shouldn't the safe call operator (?.) stop evaluating once it has been invoked on a null? Why is this not valid:
Copy code
class Nesting (val parent: Nesting? = null) {
    val map = mutableMapOf("id" to nextId ())
    override fun toString(): String = "${map["id"]}"

    companion object {
        private var count = 0
        fun nextId () = count ++
    }
}

fun main () {
    val a = Nesting (Nesting (Nesting ()))

    println (a.map)
    println (a.parent?.map.get ("id") ?: "?")
}
e
?.
works differently (and more usefully, IMO) in Kotlin than in Swift or Rust
a?.b
is equivalent to
if (a != null) a.b else null
this is useful because we can have extension functions that operate on nullable types, for example
Copy code
something?.let { listOf(it) }.orEmpty()
where
.orEmpty()
works even if the receiver is
null
c
a?.b
in Rust is written
(a ?: return null).b
in Kotlin
If you like functional programming, the Rust way of doing things is named
.bind
in the #arrow library
e
Swift-like
?.
behavior can be achieved by using
?.
instead of
.
everywhere downstream of the nullable
r
I find the kotlin behaviour much more intuitive