Bird
0
0

Find the error in this Kotlin snippet:

medium📝 Debug Q7 of 15
Kotlin - Null Safety
Find the error in this Kotlin snippet:
fun getLength(str: String?): Int {
  return str.length
}
AFunction must return String, not Int.
BCannot access length on nullable type without safe call or assertion.
Cstr should be declared as non-nullable String.
DNo error; code compiles and runs fine.
Step-by-Step Solution
Solution:
  1. Step 1: Check parameter type

    str is nullable String, so direct access to length is unsafe.
  2. Step 2: Identify missing safe call or assertion

    Accessing str.length without ?. or !! causes compile error.
  3. Final Answer:

    Cannot access length on nullable type without safe call or assertion. -> Option B
  4. Quick Check:

    Nullable property access requires ?. or !! [OK]
Quick Trick: Use ?. or !! to access nullable properties safely [OK]
Common Mistakes:
MISTAKES
  • Ignoring nullable type safety rules
  • Assuming nullable behaves like non-nullable
  • Forgetting to handle null cases

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes