13
votes

How do I write a type spec for the function that accepts, let's say, one parameter which has a default value? Something like the following:

def foo(bar \\ 10) do
  bar
end

Would it be this:

@spec foo(integer) :: integer

Or what would it be?

Thank you.

2

2 Answers

16
votes

Yes.

I would add that if your question is if there is a difference between the typespec of a function which has an argument with a default value and an argument that doesn't, then no there is no difference.

2
votes

It works as expected because you actually define two functions.

@spec foo(integer) :: integer
def foo(bar \\ 10) do
  bar
end

Is equivalent to:

def foo() do
  foo(10)
end

@spec foo(integer) :: integer
def foo(bar) do
  bar
end

So you basically end up with two functions but only one of them has @spec.