Hi, I have a question about the idiomatic usage of...
# announcements
s
Hi, I have a question about the idiomatic usage of maps. I have a map and want to retrieve a value. Before doing so I call containsKey. Afterwards I call get:
Copy code
val planetHasNumberOfSettlers = mutableMapOf<Number, Number>()
val nrOfSettlers: Number = if (planetHasNumberOfSettlers.containsKey(closePlanet.id)) {
                    planetHasNumberOfSettlers[closePlanet.id]
                } else 0
Now the compiler emits an error: Type mismatch Required Number Found Number? I get why that is, but shouldnt kotlin be able to infer that I make sure that the item is existent?
c
compiler can't be sure something hasn't changed between these calls.
a
It would be more idiomatic to use the getOrDefault() method on the map so that there is no window
c
or just:
Copy code
val nrOfSettlers: Number = planetHasNumberOfSettlers[closePlanet.id] ?: 0
s
I like the getOrDefault. thanks, thats what I have been looking for. Still its a pity kotlin cannot infer that.
c
it's not Kotlin, it's damned real world 😄
😆 2
t
if you're sure you don't use this map from another thread, and it is not decorated by any strange logic, then you can just use
!!
on your
Number?
value. at least that's what I usually do.
let me correct myself: I don't do it for default values, but only for cases when I want to use the value for something, but only if it is present