💧 Elixir Beginner

What are Elixir protocols?

Why Interviewers Ask This

This is a classic screening question for Elixir roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.

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.

Pro Tip

Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Elixir codebase.