|
| 1 | +--- |
| 2 | +layout: doc-page |
| 3 | +title: "Option-less pattern matching" |
| 4 | +--- |
| 5 | + |
| 6 | +Dotty pattern matching supports the following [extractors](https://www.scala-lang.org/files/archive/spec/2.13/08-pattern-matching.html#extractor-patterns): |
| 7 | + |
| 8 | +Boolean Pattern |
| 9 | + |
| 10 | +- Extractor defines `def unapply(x: T): Boolean` |
| 11 | +- Pattern-matching on exactly `0` patterns |
| 12 | + |
| 13 | +Product Pattern |
| 14 | + |
| 15 | +- Extractor defines `def unapply(x: T): U` |
| 16 | +- `U <: Product` |
| 17 | +- `N > 0` is the maximum number of consecutive (parameterless `def` or `val`) `_1: P1` ... `_N: PN` members in `U` |
| 18 | +- Pattern-matching on exactly `N` patterns with types `P1, P2, ..., PN` |
| 19 | + |
| 20 | +Seq Pattern |
| 21 | + |
| 22 | +- Extractor defines `def unapplySeq(x: T): U` |
| 23 | +- `U` has (parameterless `def` or `val`) members `isEmpty: Boolean` and `get: S` |
| 24 | +- `S <: Seq[V]` |
| 25 | +- Pattern-matching on any number of pattern with types `V, V, ..., V` |
| 26 | + |
| 27 | +Name Based Pattern |
| 28 | + |
| 29 | +- Extractor defines `def unapply(x: T): U` |
| 30 | +- `U` has (parameterless `def` or `val`) members `isEmpty: Boolean` and `get: S` |
| 31 | +- If there is exactly `1` pattern, pattern-matching on `1` pattern with type `S` |
| 32 | +- Otherwise `N > 0` is the maximum number of consecutive (parameterless `def` or `val`) `_1: P1` ... `_N: PN` members in `U` |
| 33 | +- Pattern-matching on exactly `N` patterns with types `P1, P2, ..., PN` |
| 34 | + |
| 35 | +In case of ambiguities, *Product Pattern* is preferred over *Name Based Pattern*. |
| 36 | + |
| 37 | +Dotty pattern matching is not special cased to case classes. Instead, allocation of Tuples and Options is avoided by desugaring case classes to use a *Product Pattern* extractor: |
| 38 | + |
| 39 | +```scala |
| 40 | +case class CC(i: Int, s: String) |
| 41 | +``` |
| 42 | + |
| 43 | +becomes |
| 44 | + |
| 45 | +```scala |
| 46 | +class CC(val i: Int, val s: String) extends Product { ... } |
| 47 | + |
| 48 | +object { |
| 49 | + def apply(i: Int, s: String): CC = new CC(i, s) |
| 50 | + def unapply(cc: CC): CC = cc |
| 51 | +} |
| 52 | +``` |
0 commit comments