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

Implementing a Protocol

The defimpl macro lets you give Elixir the implementation of a protocol for one or more types. The code that follows is the implementation of the Inspect protocol for PIDs and references.

 
defimpl​ Inspect, ​for​: PID ​do
 
def​ inspect(pid, _opts) ​do
 
"#PID"​ <> iolist_to_binary(pid_to_list(pid))
 
end
 
end
 
 
defimpl​ Inspect, ​for​: Reference ​do
 
def​ inspect(ref, _opts) ​do
 
'#Ref'​ ++ rest = :erlang.ref_to_list(ref)
 
"#Reference"​ <> iolist_to_binary(rest)
 
end
 
end

Finally, the Kernel module implements inspect, which calls Inspect.inspect with its parameter. This means that when you call inspect(self), it becomes a call to Inspect.inspect(self). And because self is a PID, this in turn ...

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