Forem

Mykolas Mankevicius
Mykolas Mankevicius

Posted on

1

[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.

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay