In the previous post, we gave an introduction to pattern matching in functions. Today we explain how to overload function in Elixir. This post is part of the functional language series, and it is based on the remarkable book Elixir In Action by Sasa Juric.
What Is Overload
Function overload is the case when we have several definitions of the same function name and arity. Elixir pattern matches input parameters and decides which definition to call. As in regular pattern matching, the order of matching is top/down direction. We overload the function that calculates VAT tax for a beer price:
We first calculate beer price in Croatia, and after that, we put the wrong input to trigger
FunctionClauseError usually indicates a bug in a program.
It is important to understand that we do not have three price functions, just one:
Error Instead Of
It is good practice to explain to users what went wrong with provided input. So last overloaded function should return an error that provided input could not be processed:
Note that we add to
key, function overloading still works because we still hit arity/1. But with arity/2, we got
- return an error instead of
- order of function overloading is top/down
- overloading works only for the same function arity