Skip to content

Commit e4bbc9b

Browse files
authored
Add note on extractor object
1 parent 484ff42 commit e4bbc9b

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

_tour/pattern-matching.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,39 @@ input match
168168

169169
In this example, name and age extract parts of the string based on the pattern. This is helpful for parsing structured text.
170170

171+
We can also use extractor objects for string pattern matching.
172+
173+
{% tabs s-interpolator-pattern-matching-2 class=tabs-scala-version %}
174+
{% tab 'Scala 2' for=s-interpolator-pattern-matching-2 %}
175+
```scala
176+
object Int {
177+
def unapply(s: String): Option[Int] = s.toIntOption
178+
}
179+
180+
val input: String = "Alice is 25 years old"
181+
182+
val (name, age) = input match {
183+
case s"$name is ${Int(age)} years old" => (name, age)
184+
}
185+
// name: String = Alice
186+
// age: Int = 25
187+
```
188+
{% endtab %}
189+
{% tab 'Scala 3' for=s-interpolator-pattern-matching-2 %}
190+
```scala
191+
object Int:
192+
def unapply(s: String): Option[Int] = s.toIntOption
193+
194+
val input: String = "Alice is 25 years old"
195+
196+
val (name, age) = input match
197+
case s"$name is ${Int(age)} years old" => (name, age)
198+
// name: String = Alice
199+
// age: Int = 25
200+
```
201+
{% endtab %}
202+
{% endtabs %}
203+
171204
## Pattern guards
172205
Pattern guards are boolean expressions which are used to make cases more specific. Just add `if <boolean expression>` after the pattern.
173206

0 commit comments

Comments
 (0)