Bird
0
0

This Kotlin code calls a Java method returning a platform type:

medium📝 Debug Q14 of 15
Kotlin - Null Safety
This Kotlin code calls a Java method returning a platform type:
val length = javaObject.getName()?.length ?: 0

What is the main benefit of using ?. here?
AIt forces the compiler to treat the value as non-null
BIt throws an exception if the value is null
CIt converts the platform type to a non-nullable type
DIt safely handles null by returning 0 instead of crashing
Step-by-Step Solution
Solution:
  1. Step 1: Identify safe call operator usage

    The ?. operator calls length only if getName() is not null.
  2. Step 2: Understand Elvis operator fallback

    If getName() is null, the expression returns 0 instead of crashing.
  3. Final Answer:

    It safely handles null by returning 0 instead of crashing -> Option D
  4. Quick Check:

    Safe call + Elvis operator prevent null crashes [OK]
Quick Trick: Use ?. and ?: to avoid null crashes with platform types [OK]
Common Mistakes:
MISTAKES
  • Thinking ?. forces non-null type
  • Assuming it throws exception on null
  • Confusing safe call with non-null assertion (!!)

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes