💧 Elixir Beginner

What are Elixir protocols?

Answer

Protocols in Elixir enable polymorphism for any data type, including types you don't own. Define a protocol: defprotocol Printable do; def print(data); end. Implement for specific types: defimpl Printable, for: Integer do; def print(n), do: IO.puts(n); end; defimpl Printable, for: List do; def print(l), do: IO.inspect(l); end. Call: Printable.print(42); Printable.print([1,2,3]). Key feature: you can implement a protocol for a type you don't control — a third-party library's struct, or built-in types. This is different from Ruby's monkey patching because protocol implementations are explicit and scoped. Elixir's standard library uses protocols extensively: Enumerable (enables Enum functions on any custom type), String.Chars (enables string interpolation), Inspect (enables IO.inspect). Protocols are the Elixir equivalent of type classes in Haskell/Scala.