Reputation: 2362
I created a map hardmapping values to false
But when I want to access it, I get offered a nullable boolean. How can I avoid it besides my suggestion down below?
object Keyboard{
val keys = Key.values().associate { it to false }.toMutableMap()
fun pressButtonForEvent(event : KeyEvent){
keys[event.key] = true
}
fun isPressed(key : Key) : Boolean {
return keys[key]
}
}
fun isPressed(key : Key) : Boolean {
return if (keys.containsKey(key)){
keys[key]!!
} else false
}
Upvotes: 2
Views: 780
Reputation: 23242
If you are unsure whether others can put keys into your map, use getOrElse
or getOrDefault
to access the values:
keys.getOrElse(key) { false }
keys.getOrDefault(key, false)
Alternatively initialize your map using a withDefault
-wrapper:, e.g.:
keys = mutableMapOf<Key, Boolean>().withDefault { false } // in the end you initialize every key with false
Accessing the value can then be achieved via getValue
:
keys.getValue(key)
If you use getValue
without withDefault
you will get an exception if there is no value for the given key. Using it with a proper withDefault
setup it will always give you the default value if there is no such key in the map.
Last but not least: if you have full control over that map and no one will ever put anything else into it, a keys[key]!!
might also be ok... In every other case keys.getValue(key)
is probably better as the exception message clearly states which key is missing whereas with !!
you just get a NullPointerException
.
Upvotes: 2