Lets say we are writing a function that says “Hello” to people. In Elixir we might write something like this;
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;
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;
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;
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