Bird
0
0

What is wrong with this Kotlin code?

medium📝 Debug Q6 of 15
Kotlin - Null Safety
What is wrong with this Kotlin code?
val message: String? = null
println(message.length?.toString())
AThere is no error in this code
BThe safe call operator is used incorrectly on <code>length</code>
CThe <code>toString()</code> method cannot be called on an Int
DYou cannot access <code>length</code> directly on a nullable variable without safe call
Step-by-Step Solution
Solution:
  1. Step 1: Analyze variable type

    message is nullable (String?).
  2. Step 2: Check property access

    Accessing length directly on a nullable variable without safe call is invalid.
  3. Step 3: Identify error

    The code should use message?.length to safely access length.
  4. Final Answer:

    You cannot access length directly on a nullable variable without safe call -> Option D
  5. Quick Check:

    Nullable variables require safe call for member access [OK]
Quick Trick: Nullable variables need ?. before member access [OK]
Common Mistakes:
MISTAKES
  • Using safe call on property instead of variable
  • Assuming toString() cannot be called on Int
  • Ignoring null safety rules

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes