https://kotlinlang.org logo
Title
s

sveri

11/23/2017, 7:15 PM
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:
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

Czar

11/23/2017, 7:19 PM
compiler can't be sure something hasn't changed between these calls.
a

andyb

11/23/2017, 7:20 PM
It would be more idiomatic to use the getOrDefault() method on the map so that there is no window
c

Czar

11/23/2017, 7:21 PM
or just:
val nrOfSettlers: Number = planetHasNumberOfSettlers[closePlanet.id] ?: 0
s

sveri

11/23/2017, 7:22 PM
I like the getOrDefault. thanks, thats what I have been looking for. Still its a pity kotlin cannot infer that.
c

Czar

11/23/2017, 7:22 PM
it's not Kotlin, it's damned real world 😄
😆 2
t

tamas.barta

11/24/2017, 1:18 PM
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