How To Overload Function In Elixir — Tentamen Software Testing Blog

Karlo Smid
2 min readFeb 16, 2021

--

Image by Loren Elkin from Pixabay

TL;DR

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.

Run for overloaded price function

FunctionClauseError 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 FunctionClauseError

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

Function overload with default clause.

Remember

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

Originally published at https://blog.tentamen.eu on February 16, 2021.

--

--