Confusing format of function documentation?

I am starting out with Elixir and I have some problems understanding the documentation at

https://hexdocs.pm/elixir/master/IO.html#inspect/2

  1. According to the doc there is an inspect/2 and inspect/3 but no inspect/1. Therefore I expect that iex> IO.inspect 9 would return an error (no function with arity 1) however it does not. What am I missing?

  2. What do the backslashes and square brackets imply in the documentation for inspect/1? Perhaps this answers the first question. I know square brackets mean a linked list, obviously, but I haven’t found a definition for the backslashes. This should be easier to look up in the documentation.

inspect(item, opts \\ [])
inspect(item, Keyword.t) :: item when item: var

Thanks for any input!

1 Like

The backslashes are used for default arguments.

So, calling IO.inspect("foo") is the same as calling IO.inspect("foo", []) which means that you are calling the 2 arity function when passing only one argument.

2 Likes

The backslash is for setting the default value for the param, so inspect(9) is really inspect(9,[]).
The is some sugar on top of the opts \\ [] stuff since its so common.

def func(arg1, opts \\ []) do
end
func("arg1")
func("arg1", [foo: true, baz: 1])
func("arg1", foo: true, baz: 4)
2 Likes