Bala
Bala

Reputation: 11244

What is the significance of Protocol in elixir?

Having used the term Protocol with network (http, ftp etc), I am confused with its usage in Elixir. For e.g. there are references to Enum module and Enumerable Protocol. Elixir documentation says Protocols are a mechanism to achieve polymorphism in Elixir.

Aren't they just a module with a set of methods/functions? Are there any distinctions?

Upvotes: 3

Views: 275

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Think of protocol as of interface in Java / abstract class in Python (in fact, java interfaces and specifically python abstract classes are more to @behaviour, but anyway.)

defprotocol Sound do
  def make_sound(data)
end

defmodule Dog do
  defstruct name: "Donny"
end

defimpl Sound, for: Dog do
  def make_sound(data) do
    "#{data.name} barks “woof”"
  end
end

defmodule Cat do
  defstruct name: "Hilly"
end

defimpl Sound, for: Cat do
  def make_sound(data) do
    "#{data.name} murrs “meow”"
  end
end

and there in the code:

%Dog{} |> Sound.make_sound
#⇒ "Donny barks “woof”"

or:

pet = .... # complicated code loading a struct
pet |> Sound.make_sound # here we don’t care what pet we have

This mechanism is used in string interpolation:

"#{5}"

The above works because Integer has the implementation of String.Chars. The implementation just calls

WHATEVER_IN_#{} |> String.Chars.to_string

to get a binary. For instance. for aforementioned Dog module we might implement String.Chars:

defimpl String.Chars, for: Dog do
  def to_string(term) do
    "#{term.name} barks “woof”"
  end
end

Now one might interpolate dogs:

"#{%Dog{}}"
#⇒ "Donny barks “woof”"

Upvotes: 6

Related Questions