Elixir Default Arguments
A default argument is a fallback value a function uses when the caller leaves that argument out. You write the fallback after the argument name, using two backslash characters.
An omitted name falls back to friend
The hello function gives name a default of "friend". A call with no argument uses that default.
defmodule Greeter do
def hello(name \\ "friend"), do: "Hello, #{name}"
end
IO.puts(Greeter.hello())
IO.puts(Greeter.hello("Ana"))A default quantity of one keeps the price unchanged
The total function defaults quantity to 1. Passing a quantity replaces the default and changes the total.
defmodule Order do
def total(price, quantity \\ 1), do: price * quantity
end
IO.puts(Order.total(10))
IO.puts(Order.total(10, 3))Later defaults can be left out one by one
This function has two defaults, for prefix and suffix. Each call passes one more argument than the call before it.
defmodule Label do
def make(text, prefix \\ "Note", suffix \\ "!"), do: "#{prefix}: #{text}#{suffix}"
end
IO.puts(Label.make("Ready"))
IO.puts(Label.make("Ready", "Alert"))
IO.puts(Label.make("Ready", "Alert", "."))Example
defmodule Greeter do
def welcome(name \\ "friend", city \\ "Seattle"), do: "Welcome, #{name} from #{city}"
end
IO.puts(Greeter.welcome())
IO.puts(Greeter.welcome("Ana"))
IO.puts(Greeter.welcome("Ana", "Denver"))Key points
- Default: a fallback value written in the function definition.
- Syntax: the two backslash characters \\ separate the argument name from its default value.
- Omitted argument: the function uses the default value in place of the missing one.
- Given argument: a value the caller passes replaces the default.
- Placement: an argument with a default can sit after arguments that have no default.
- Choice: a caller may pass some trailing arguments and leave the later ones out.
In this example, welcome has a default for both name and city. The first call uses both defaults, the second call replaces only the name, and the third call replaces both values.
Note
in Elixir, the default is chosen when the call leaves the argument out, not when the value is empty.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A function is defined as def hello(name \\ "friend"), do: "Hello, #{name}". What does hello() return?