Bird
0
0

You have a Java method fun getUser(): User returning a platform type. You want to safely get the user's email or return "unknown" if null. Which Kotlin code correctly handles this?

hard📝 Application Q15 of 15
Kotlin - Null Safety
You have a Java method fun getUser(): User returning a platform type. You want to safely get the user's email or return "unknown" if null. Which Kotlin code correctly handles this?
Aval email = getUser().email ?: "unknown"
Bval email = getUser()?.email ?: "unknown"
Cval email = getUser().email!!
Dval email = getUser().email
Step-by-Step Solution
Solution:
  1. Step 1: Recognize platform type and possible nulls

    getUser() returns a platform type; email might be null.
  2. Step 2: Use safe call and Elvis operator

    Using ?. safely accesses email; ?: provides fallback "unknown" if null.
  3. Final Answer:

    val email = getUser()?.email ?: "unknown" -> Option B
  4. Quick Check:

    Safe call + fallback handles null platform types safely [OK]
Quick Trick: Use ?. with ?: to safely access nullable Java values [OK]
Common Mistakes:
MISTAKES
  • Using non-null assertion (!!) risking runtime crash
  • Ignoring possible null from platform type
  • Not providing fallback for null values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes