What is the idiomatic way of matching for not
nil in Elixir?
defp halt_if_not_signed_in(conn, signed_in_account) when signed_in_account != nil do
defp halt_if_not_signed_in(conn, signed_in_account) when not is_nil(signed_in_account) do
If there is a preferred way does anybody know the reason?
Personally I prefer the first way because it reads more naturally and takes less horizontal space but examples I’ve seen have used
not is_nil(...) and I am wondering why.
Personally I do:
defp halt_if_not_signed_in(conn, nil), do: :whatever
defp halt_if_not_signed_in(conn, signed_in_account) do
Unless you just want
nil to error out, in which case I’d optimally do a precise match:
defp halt_if_not_signed_in(conn, signed_in_account) when is_binary(signed_in_account)
agreed. I find using pattern matching to handle this is very readable.
I’ve helped introduce two Java engineers to Elixir and they both found this a really useful language feature, especially as they discovered some of the powerful variations of pattern matching.
As for other uses of not is_nil(val) vs val != nil I’d say just pick one and be consistent within your project. Personally not is_nil(val) is not my favorite.
I’m personally a fan of
val != nil because
nil is just an atom, so I don’t even know why it has a specialized function like
is_nil/1 anyway, especially since the empty list
 is the
nil value on the system, those confused me for a bit when I started Elixir (
nil should have been
 as the empty list is named
nil standardly, not