Difference between using getOrDefault() and elvis operator on a Map

Viewed 138

Could someone explain why these two lines act differently? activeGames is a MutableMap<String, Game>.

val game = activeGames.getOrDefault(id, Game(id))

val game = activeGames[id]?:Game(id)

For whatever reason, whenever I pass in the id key for a game that I know exists, calling getOrDefault always does the default behavior of creating a new game instead of grabbing the game from the map. But the line with the elvis operator works like I expect, and gets the existing game from the map.

I am instantiating activeGames with:

val activeGames = mutableMapOf<String, Game>()

1 Answers

I think you have a problem with the id you pass to getOrDefault try debugging your code and throw an exception if activeGames.containsKey(id) returns false.

if I reproduce your logic that you describe this what we expect to get and I just test it and this is the outcome.

data class Game(val gameId: String)

fun main(args: Array<String>) {
    val id = "bla"
    val activeGames = mapOf(id to Game(id))
    val game1 = activeGames.getOrDefault(id, Game(id))
    val game2 = activeGames[id] ?: Game(id)
    println("game1 : $game1")
    println("game2 : $game2")
}

output:

game1 : Game(gameId=bla)
game2 : Game(gameId=bla)
Related