DEV Community

Mykolas Mankevicius
Mykolas Mankevicius

Posted on

[TIL] Elixir Map/Keyword.get default value is eager

For some reason, maybe php/javascript i though that

Map.get(opts, :key, "default")
Keyword.get(opts, :key, "default")
Enter fullscreen mode Exit fullscreen mode

The default value will only get evaluated if you there is no default value provided in the map/keyword list.

Considering it now it seems silly, but it's a little lesson i had to learn the hard way.

Here's what i did:

Keyword.get(opts, :key, SomeRepo.total_products(user.id))
Enter fullscreen mode Exit fullscreen mode

Which obviously calls the repo every time you are trying to access the :key, what i wanted is to only call the repo when the value is nil

And here's the fix to only evaluate the repo call if the keyword is set to nil

show_intro? =
  opts
  |> Keyword.get(:show_intro?)
  |> show_intro?(user.id)

defp show_intro?(nil, id), do: Products.total_by_user(id) == 0
defp show_intro?(show, _), do: show
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
jclem profile image
Jonathan Clem • Edited

Worth also taking a look at Keyword.get_lazy/3.