Be careful with Kotlin Scope Functions

--

The Curious Case of ?.let {} ?: run {}

Try this code :

fun main() {
val theCase: Int? = 1
theCase?.let {
fun1()
fun2()
} ?: run {
funError()
}
}

fun fun1() {
println(
"fun1")
}

fun fun2(): Unit? {
// return println("fun2")
return null
}

fun funError(){
println(
"funError")
}

The result :

fun1
funError

So the funError() was called - but it shouldn’t?

Play with the code and change the fun2() to :

fun fun2(): Unit? {
return println("fun2")
// return null
}

Generally speaking, funError() should be called only when (?)

val theCase: Int? = null

Not really …

You can read more about it (and many others) in details here :

--

--