For this behavior I think you'd be better of using `map[key] || default_value`, 
or even `Map.get(map, key) || default_value`. Docs for `Map.get/3` are pretty 
clear about when it returns default value.

-------- Original Message --------
On 22 Jun 2022, 14:25, Nganga Mburu wrote:

> I've found myself and seen others expecting to receive the default value from 
> `Map.get/3` when the value is `nil`.
>
> An example is:
> `Map.get(%{name: nil}, :name, "John")`
>
> Expected it to return "John" but it returns `nil`
>
> My thinking is since the default value is for the key then when the key value 
> is `nil` we should be able to get the default value.
>
> The change in code could be as below:
> ```
> def get(map, key, default \\ nil) do
> case map do
> %{^key => value} when is_nil(value) ->
> default
>
> %{^key => value} ->
> value
>
> %{} ->
> default
>
> other ->
> :erlang.error({:badmap, other}, [map, key, default])
> end
> end
> ```
>
> --
> You received this message because you are subscribed to the Google Groups 
> "elixir-lang-core" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to elixir-lang-core+unsubscr...@googlegroups.com.
> To view this discussion on the web visit 
> [https://groups.google.com/d/msgid/elixir-lang-core/9d31c830-8005-4a76-a1f9-dbea2d841ea4n%40googlegroups.com](https://groups.google.com/d/msgid/elixir-lang-core/9d31c830-8005-4a76-a1f9-dbea2d841ea4n%40googlegroups.com?utm_medium=email&utm_source=footer).

-- 
You received this message because you are subscribed to the Google Groups 
"elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to elixir-lang-core+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/elixir-lang-core/Vn4lCPxz8hge1GGBTOw5gKy_9JfNcg4Zau0qqixm43Qjl73cEetpnKkhjYaadr9tUNRnBCBXiCeesQRjUSbXT9OXNuwHXXLL7k3rZ6STH3Y%3D%40pm.me.

Reply via email to