Defining a Protocol

Protocol definitions are very similar to basic module definitions. They can contain module- and function-level documentation (@moduledoc and @doc), and they will contain one or more function definitions. However, these functions will not have bodies—they are there simply to declare the interface that the protocol requires.

For example, here is the definition of the Inspect protocol:

 defprotocol​ Inspect ​do
  @fallback_to_any true
 def​ inspect(thing, opts)
 end

Just like a module, the protocol defines one or more functions. But we implement the code separately.

Get Programming Elixir ≥ 1.6 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.