Elixir Default Params

Learn how to assign a default parameter or argument to your Elixir functions

Lets say we are writing a function that says “Hello” to people. In Elixir we might write something like this;

defmodule Greeter do
  def hello(name) do
    IO.inspect("Hello #{name}!")
  end
end

So when we call Greeter.hello("Jo") our console will put out “Hello Jo!”.

We love our new function, and use it often, but we realise that 90% of the uses are saying Greeter.hello("there") because we don’t know the person’s name.

It would be much nicer to call Greeter.hello and have it do “Hello there!” and when we know the name we can pass it in like normal.

This is where setting default values for our function’s parameters can be incredibly useful, in Elixir we do it like this;

defmodule Greeter do
  def hello(name \\ "there") do
    IO.inspect("Hello #{name}!")
  end
end

The name \\ "there" basically says; If a value is passed into me, excellent, use that. If there isn’t then set me to be “there”.

Our final implementation means we can do the following;

iex> Greeter.hello
"Hello there!"
iex> Greeter.hello("Zchen")
"Hello Zchen!"

Not just Strings

It doesn’t have to be a simple data type like a String that you set stuff to, you can pass entire modules in as default params.

To borrow from our last example, we could create the following;

defmodule Logger do
  def log(message \\ Greeter) do
    message.hello
  end
end

Here we have made Logger.log/1 which lets you pass in the module you want to use, in this case any module that can access a hello/1 function would be fine and here if we call Logger.log by default it will give us “Hello there!” back because it has called hello/1 on Greeter.

Recent posts View all

Ruby

Using the 'it' Gem to add links to translations

How to can use the 'it' Gem to add links to your translations

Slack

Custom Startup Messages on Slack

How to set a custom start up message on your team's Slack channel. Part of our Slack mini series.