Back to questions
JuniorTheoryCommon
What does the program print (lines separated by spaces)?
fun main() {
val ages = mapOf("Ann" to 30, "Bob" to 25)
println(ages["Ann"])
println(ages["Eve"])
}30 null
- Expecting an exception, as with a list index past the end:
[]on a map returnsnullfor a missing key, and onlygetValuethrowsNoSuchElementException. - Expecting
0for a missing number:nullmeans the map holds nothing under"Eve";getOrDefault("Eve", 0)or?: 0gives a zero.
- How would you print
0instead ofnullfor a name that is not in the map? - What does
ages.getValue("Eve")do, and when would you choose it over[]?