Bird
0
0

Given var input: String? = "123", which code safely converts it to an integer or returns 0 if null or invalid?

hard📝 Application Q9 of 15
Kotlin - Null Safety
Given var input: String? = "123", which code safely converts it to an integer or returns 0 if null or invalid?
Aval number = input?.toInt()
Bval number = input?.toInt() ?: 0
Cval number = input.toInt()
Dval number = input!!.toInt()
Step-by-Step Solution
Solution:
  1. Step 1: Handle nullable input safely

    Use safe call ?. to avoid calling toInt() on null.
  2. Step 2: Provide default value with elvis operator

    ?: 0 returns 0 if the left side is null.
  3. Final Answer:

    val number = input?.toInt() ?: 0 -> Option B
  4. Quick Check:

    Safe call plus elvis operator handles null and invalid safely [OK]
Quick Trick: Use ?. with ?: to safely convert nullable strings [OK]
Common Mistakes:
MISTAKES
  • Using !! risking exceptions on null
  • Calling toInt() directly on nullable
  • Ignoring default value for null cases

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes