Bird
0
0

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

medium📝 Debug Q6 of 15
Kotlin - Null Safety
This Kotlin code calls a Java method returning a platform type:
val text: String = javaApi.getText()
println(text.length)

It sometimes crashes with NullPointerException. How to fix it?
AChange text type to String? and check for null
BAdd !! after getText() call
CUse lateinit var instead of val
DNo fix needed, it's a Kotlin bug
Step-by-Step Solution
Solution:
  1. Step 1: Identify cause of NullPointerException

    Assigning platform type to non-nullable String causes crash if Java returns null.
  2. Step 2: Fix by using nullable type and null check

    Changing to String? allows safe null handling and prevents crash.
  3. Final Answer:

    Change text type to String? and check for null -> Option A
  4. Quick Check:

    Nullable type prevents platform type null crashes [OK]
Quick Trick: Use nullable types to avoid platform type null crashes [OK]
Common Mistakes:
MISTAKES
  • Using !! which throws exceptions
  • Using lateinit without initialization
  • Blaming Kotlin instead of null safety

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes