🤩 Better defaults with Enum.find/3

You’re familiar with Enum.find/2. It returns the value for which the fun is true:

Enum.find([1, 2, 3, 4], fn i -> i == 3 end)
# => 3

But when a value can’t be found, it returns nil.

Enum.find([1, 2, 3, 4], fn i -> i == 5 end)
# => nil

Of course, that’s not always desirable, since nil values have a way of propagating through our systems. 😞

So, sometimes it’s nicer to have a more clear value returned when nothing is found:

Enum.find([1, 2, 3, 4], :not_found, fn i -> i == 3 end)
# => :not_found

That’s much better!

And that’s especially helpful if Enum.find/3 is just an implementation detail of a larger function in your domain:

@spec get_user(String.t()) :: User.t() | :not_found
def get_user(id) do
  all_users()
  |> Enum.find(:not_found, fn user ->
    user.id == id
  end)
end

Want the latest Elixir Streams in your inbox?

    No spam. Unsubscribe any time.