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" <> IO.iodata_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" <> IO.iodata_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, ...
Get Programming Elixir 1.2 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.