https://kotlinlang.org logo
#getting-started
Title
# getting-started
l

lee.crawford

01/21/2023, 6:47 PM
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

ephemient

01/21/2023, 6:48 PM
?.
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

CLOVIS

01/22/2023, 1:24 PM
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

ephemient

01/22/2023, 3:02 PM
Swift-like
?.
behavior can be achieved by using
?.
instead of
.
everywhere downstream of the nullable
r

Rob Elliot

01/23/2023, 10:09 AM
I find the kotlin behaviour much more intuitive
7 Views