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

Mykolas Mankevicius - May 29 '23 - - Dev Community

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
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player