Bird
0
0

Consider this Kotlin code calling a Java method returning a platform type:

medium📝 Predict Output Q13 of 15
Kotlin - Null Safety
Consider this Kotlin code calling a Java method returning a platform type:
val length = javaObject.getName().length

What happens if getName() returns null at runtime?
AThe code throws a NullPointerException at runtime
BThe code fails to compile due to null safety
CThe code compiles and runs safely, length is 0
DThe code returns length as -1
Step-by-Step Solution
Solution:
  1. Step 1: Understand platform type nullability

    Platform types can be null but Kotlin treats them as non-nullable unless specified.
  2. Step 2: Analyze code behavior

    Calling length on a null value causes a NullPointerException at runtime.
  3. Final Answer:

    The code throws a NullPointerException at runtime -> Option A
  4. Quick Check:

    Platform types can cause runtime NPE if null used unsafely [OK]
Quick Trick: Accessing platform type without null check risks NPE [OK]
Common Mistakes:
MISTAKES
  • Assuming Kotlin prevents runtime null errors
  • Thinking length returns 0 for null
  • Expecting compile-time error for platform types

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes