Bird
0
0

How can you safely get the length of a nullable string str using the Elvis operator?

hard📝 Application Q9 of 15
Kotlin - Operators and Expressions

How can you safely get the length of a nullable string str using the Elvis operator?

Aval length = str.length ?: 0
Bval length = str ?: str.length
Cval length = str ?: 0.length
Dval length = str?.length ?: 0
Step-by-Step Solution
Solution:
  1. Step 1: Use safe call operator for nullable

    str?.length safely accesses length or returns null if str is null.
  2. Step 2: Use Elvis operator to provide default

    ?: 0 returns 0 if str?.length is null.
  3. Final Answer:

    val length = str?.length ?: 0 -> Option D
  4. Quick Check:

    Safe call plus Elvis gives safe default length [OK]
Quick Trick: Use ?. with ?: to safely handle nullable properties [OK]
Common Mistakes:
MISTAKES
  • Calling length directly on nullable
  • Misplacing Elvis operator
  • Using invalid syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes