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)
endTYPES AND PATTERN MATCHING
dynamic typing with strong guarantees, and a type system arriving
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