I am reading a book and found the below example.
defmodule Params do
def func(p1, p2 \\ 2)
def func(p1, p2) when is_list(p1) do
IO.inspect "You said #{p2} with a list"
end
def func(p1, p2) do
IO.inspect "You passed in #{p1} and #{p2}"
end
end
And I ran it like:
mm$ iex params.exs
Erlang/OTP 21 [erts-10.0.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [hipe] [dtrace]
Interactive Elixir (1.6.6) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> Params.func 1
"You passed in 1 and 2"
"You passed in 1 and 2"
iex(2)> Params.func 1, 5
"You passed in 1 and 5"
"You passed in 1 and 5"
iex(3)> Params.func [99]
"You said 2 with a list"
"You said 2 with a list"
iex(4)>
I am not getting why there is function definition without any body in it? Can anyone explain why is that needed? If comment out # def func(p1, p2 \\ 2)
, still the program works as expected.