Part 1 · 1 chapters · ~8 min

Types and Pattern Matching

Dynamic but strong typing, structs and their compile-time checks, pattern matching in function heads, case, cond and with, guards, binaries and bitstring matching, protocols for polymorphism, typespecs and Dialyzer, and the set-theoretic type system introduced from Elixir 1.17.

2

Dispatch by shape

code
defmodule Payout do
  defstruct [:id, :amount_kobo, :state, :rail_ref]
  @type t :: %__MODULE__{id: String.t(), amount_kobo: pos_integer(), state: :pending | :settled | :failed, rail_ref: String.t() | nil}

  @spec label(t()) :: String.t()
  def label(%Payout{state: :settled, rail_ref: ref}), do: "Sent (#{ref})"
  def label(%Payout{state: :failed}), do: "Failed"
  def label(%Payout{state: :pending}), do: "Processing"
end

# binary matching: parse a length-prefixed frame
def parse(<<len::16, payload::binary-size(len), rest::binary>>), do: {:ok, payload, rest}
def parse(bin), do: {:more, bin}

# protocols: polymorphism without inheritance
defprotocol Ledgerable do
  def postings(event)
end
TYPES AND PATTERN MATCHING
dynamic typing with strong guarantees, and a type system arriving
dynamic, strongNo implicit conversions: "1" + 1raises.structs%Transfer{} with fixed keys;compile-time key checks.pattern matchingDestructure maps, structs, lists,binaries in heads.typespecs + Dialyzer@spec annotations checked byDialyzer (success typing).set-theoretic typesElixir 1.17+ type checker:gradual, inferred, warnings.binariesMatch on bytes: parse protocols infunction heads.
swipe the figure sideways, or tap expand for full screen
1/4
strong but dynamic
Types are checked at run time and never coerced; bugs surface as clear errors rather than silent conversions.
dynamic, no coercion"1" + 1 raises