Bird
0
0

What will be the output of this Kotlin code?

medium📝 Predict Output Q13 of 15
Kotlin - Null Safety
What will be the output of this Kotlin code?
fun main() {
    val text: String? = null
    println(text?.length ?: "No text")
}
A0
BCompilation error
Cnull
DNo text
Step-by-Step Solution
Solution:
  1. Step 1: Understand safe call operator usage

    The text?.length safely accesses length only if text is not null.
  2. Step 2: Evaluate the Elvis operator

    Since text is null, text?.length is null, so the Elvis operator ?: returns "No text".
  3. Final Answer:

    No text -> Option D
  4. Quick Check:

    Safe call + Elvis operator returns fallback [OK]
Quick Trick: Safe call with Elvis returns fallback if null [OK]
Common Mistakes:
MISTAKES
  • Expecting 0 instead of fallback string
  • Confusing safe call with normal call
  • Thinking code causes error due to null

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes