[TIL] Elixir Map/Keyword.get default value is eager
For some reason, I misunderstood that the default values in the following Elixir code would only be assessed if no default value was provided in the map/keyword list:
Map.get(opts, :key, "default")
Keyword.get(opts, :key, "default")
Upon reflection, this misconception seems trivial, but it was a lesson I had to learn through experience.
Here’s what I initially did:
Keyword.get(opts, :key, SomeRepo.total_products(user.id))
Clearly, this leads to calling the repository every time you attempt to access :key. My intention was for the repository to be called only when the value was nil.
And here’s the correction to evaluate the repository call only when 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