Bird
0
0

Given the following Kotlin code, what will be the output?

hard📝 Application Q15 of 15
Kotlin - Operators and Expressions

Given the following Kotlin code, what will be the output?

fun getName(user: Map): String {
    return user["firstName"] ?: user["nickname"] ?: user["lastName"] ?: "Anonymous"
}

val user1 = mapOf("firstName" to null, "nickname" to null, "lastName" to "Smith")
println(getName(user1))
AAnonymous
BCompilation error
CSmith
Dnull
Step-by-Step Solution
Solution:
  1. Step 1: Evaluate the map values in order

    firstName and nickname are null, so Elvis operator moves to lastName, which is "Smith".
  2. Step 2: Determine the returned value

    Since lastName is not null, the function returns "Smith".
  3. Final Answer:

    Smith -> Option C
  4. Quick Check:

    Elvis chain returns first non-null: Smith [OK]
Quick Trick: Elvis chains pick first non-null map value [OK]
Common Mistakes:
MISTAKES
  • Assuming it returns Anonymous despite lastName present
  • Confusing null with string "null"
  • Thinking map access causes error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes