Predict the output
What happens when you compile this?
class Profile {
var nickname: String? = null
fun shout(): Int {
if (nickname != null) {
return nickname.length
}
return 0
}
}Hint 1 of 1
Is nickname a local val or a mutable property?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A Compile error: smart cast is impossible because nickname is a mutable property
Correct. The property could change between the check and the use.
Why not the others?
- B It compiles and returns the length. The compiler can't prove nickname is still non-null.
- C It compiles, but throws NullPointerException at runtime. It doesn't compile at all.
- D Compile error: nickname must be lateinit. lateinit is unrelated.