Search⌘ K

Protocols

Explore the concept of protocols in Elixir and how they enable polymorphic functions to work with multiple data types. Understand how protocols differ from behaviours and how you can implement and extend functionality across modules without modifying their source code.

Introduction

We’ve used the inspect function many times in this course. It returns a printable representation of any value as a binary, which is what we call strings.

But let’s stop and think for a minute. Just how can Elixir, which doesn’t have objects, know what to call to do the conversion to a binary? We can pass inspect anything, and Elixir somehow makes sense of it. It could be done using guard clauses:

def inspect(value) when is_atom(value), do: ...
def inspect(value) when is_binary(value), do: ...
:       :

But there’s a better way.

Elixir has the concept of protocols. A protocol is a little ...