How To Overload Function In Elixir — Tentamen Software Testing Blog

Image by Loren Elkin from Pixabay


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 .

Run for overloaded price function

usually indicates a bug in a program.

Whole Function

It is important to understand that we do not have three price functions, just one:

The overloaded function is the whole function.

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 additional , function overloading still works because we still hit arity/1. But with arity/2, we got

Function overload with default clause.


  • return an error instead of
  • order of function overloading is top/down
  • overloading works only for the same function arity

Originally published at on February 16, 2021.