# Default parameters in a spawned function

In this module if I call Test.func directly, the default parameter is picked up, but if I run Test.start, it is ignored:

``````defmodule Test do

def start do
_pid = spawn(__MODULE__, :func, [[], []])
end

def func(list, index \\ 0 ) do
IO.puts "index: #{index}, list: #{inspect list}"
end
end
``````
``````iex(1)> Test.func([:a])
index: 0, list: [:a]
:ok
iex(2)> Test.start
#PID<0.94.0>
index: , list: []
iex(3)>
``````

Is there any way around this?

When you `spawn` your function, you are giving 2 arguments, so there is no need to apply the default ones, it should work after changing the spawn: `spawn(__MODULE__, :func, [[]])`

Also, are those backslashes in your code as well, or are they a copypaste accident?

The extra backslashes were there because I couldn’t get the back ticks to work from my iPad. Someone else must have added them.

But I need that default value when the func is called. I need to use the index as an index into the list, and `elem(index, list)` complains rather vociferously when `index` doesn’t have a value.

(And the backticks seem to be working now…)

I had inserted the backticks for you, it was easier for me to read the code then

And to make my example from the first post more clear:

``````defmodule Test do
def start do
_pid = spawn(__MODULE__, :func, [[]])
end

def func(list, index \\ 0 ) do
IO.puts "index: #{index}, list: #{inspect list}"
end
end
``````

This should do what you want. In your example, you are overriding the default, by providing 2 arguments in the list of arguments. If you wan’t the default to kick in, you are not allowed to provide more than one argument.

Your call in spawn, were like `func([], [])`.

2 Likes