gutenmorgenuhu
gutenmorgenuhu

Reputation: 2362

MutableMap<Key, Boolean> returns nullable Boolean? for value access with key

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]
    }

}

Suggestion to solve it (but I dont like it)

fun isPressed(key : Key) : Boolean {
    return if (keys.containsKey(key)){
        keys[key]!!
    } else false
}

Upvotes: 2

Views: 780

Answers (1)

Roland
Roland

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

Related Questions