O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 22Protocols—Polymorphic Functions

We have used the inspect function many times in this book. It returns a printable representation of any value as a binary (which is what we hard-core folks call strings).

But 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? You 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 like the behaviours we saw in the previous chapter in that it defines the functions that must be provided ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required