Predict the output
What does this print?
fun main() {
val name: String? = null
val length = name?.length ?: -1
println(length)
try {
println(name!!.length)
} catch (e: NullPointerException) {
println("NPE")
}
}Hint 1 of 1
What does name?.length return for null?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A -1, then NPE
Correct. The safe call gives null, ?: supplies -1, and !! throws NullPointerException.
Why not the others?
- B 0, then NPE. ?. returns null, not 0.
- C -1, then 0. !! on null throws.
- D It doesn't compile. All of this is valid Kotlin.