Skip to content
Commitwise
Menu

Pattern matching

Checking a value's shape (its type, case or contents) and pulling data out of it in one step.

Definition

Pattern matching combines a test and a destructuring. Swift matches enum cases with their associated values (case .failed(let message)), Kotlin checks types in when with smart casts (is Failed ->), and Java 21 supports type and record patterns in switch (case Failed(var message)). Combined with enums or sealed types, the compiler can check that every possible shape is handled.

In practice

case Loaded(var products) when products.isEmpty() -> "No results" matches only loaded states with an empty list.

Learn it in context

Lessons that use this term.

Related terms

Esc

Type to search the whole site.