Bird
0
0

Examine this Kotlin code snippet calling a Java method that returns a platform type:

medium📝 Debug Q7 of 15
Kotlin - Null Safety
Examine this Kotlin code snippet calling a Java method that returns a platform type:
val textLength = javaApi.getDescription().length

What issue might occur if getDescription() returns null at runtime?
AThe length will be inferred as -1 indicating a null value.
BThe code will safely return 0 as the length without any exception.
CThe Kotlin compiler will prevent compilation due to unsafe call on a platform type.
DA NullPointerException will be thrown because Kotlin assumes the platform type is non-null.
Step-by-Step Solution
Solution:
  1. Step 1: Understand platform types

    Platform types come from Java and have unknown nullability, so Kotlin treats them as if they could be nullable or non-nullable.
  2. Step 2: Analyze the code

    The code calls getDescription() and immediately accesses length without null checks.
  3. Step 3: Runtime behavior

    If getDescription() returns null, accessing length on null causes a NullPointerException at runtime.
  4. Final Answer:

    A NullPointerException will be thrown because Kotlin assumes the platform type is non-null. -> Option D
  5. Quick Check:

    Calling methods on platform types without null checks risks NullPointerException [OK]
Quick Trick: Platform types can be null; always check before accessing members [OK]
Common Mistakes:
MISTAKES
  • Assuming platform types are always non-null and safe to use directly
  • Expecting Kotlin compiler to catch nullability issues on platform types
  • Believing Kotlin automatically returns default values for null platform types

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes