Blog Post: 10 Elixir gotchas

Got a new gotcha today

Elixir’s ++/2 operator (list concatenation) has a special clause: If the right-hand side is not a list, the operation returns that right-hand side value instead of raising an error.

Never knew about it. Did bite me. Type checker did not warn that the enumeration would possibly
raise an exception. :frowning:

iex(1)> [] ++ nil
nil
iex(2)> [] ++ :foo
:foo
iex(3)> [] ++ "bla"
"bla"

The source in erlang is clear. This is the comment on the nil as right-hand side:

if (is_nil(lhs)) {
        /* This is buggy but expected, `[] ++ 'not_a_list'` has always resulted
         * in 'not_a_list'. */
        return rhs;

Doubt I like the behavior, but alas…there it is.

7 Likes