Map.get/3 behavior question

I was expecting a different behavior from Map.get/3 :

iex(1)> Map.get(%{passed: nil}, :passed, 1)
nil

Looks like if the key is present, even if nil, you don’t get the default. After reading the docs, I see that it is specified there. How would you return 1 in the example above? Any other solutions?

You can use the operator || to get its second operand if the first is falsy (nil or false).

And rely on the Access protocol to write: map[:passed] || 1 (or Map.get(map, :passed) || 1 if you prefer)

6 Likes