Skip to content

Commit 183ebbf

Browse files
authored
Add documentation for Pattern Matching on String
1 parent ad2c724 commit 183ebbf

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

_tour/pattern-matching.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,36 @@ println(showNotification(someVoiceRecording)) // prints You received a Voice Re
138138

139139
The function `showNotification` takes as a parameter the abstract type `Notification` and matches on the type of `Notification` (i.e. it figures out whether it's an `Email`, `SMS`, or `VoiceRecording`). In the `case Email(sender, title, _)` the fields `sender` and `title` are used in the return value but the `body` field is ignored with `_`.
140140

141+
## Matching on String
142+
143+
The `s`-interpolator allows embedding variables in strings and is also useful for pattern matching.
144+
145+
{% tabs s-interpolator-pattern-matching class=tabs-scala-version %}
146+
{% tab 'Scala 2' for=s-interpolator-pattern-matching %}
147+
```scala
148+
val input: String = "Alice is 25 years old"
149+
150+
input match {
151+
case s"$name is $age years old" => s"$name's age is $age"
152+
case _ => "No match"
153+
}
154+
// Result: "Alice's age is 25"
155+
```
156+
{% endtab %}
157+
{% tab 'Scala 3' for=s-interpolator-pattern-matching %}
158+
```scala
159+
val input: String = "Alice is 25 years old"
160+
161+
input match
162+
case s"$name is $age years old" => s"$name's age is $age"
163+
case _ => "No match"
164+
// Result: "Alice's age is 25"
165+
```
166+
{% endtab %}
167+
{% endtabs %}
168+
169+
In this example, name and age extract parts of the string based on the pattern. This is helpful for parsing structured text.
170+
141171
## Pattern guards
142172
Pattern guards are boolean expressions which are used to make cases more specific. Just add `if <boolean expression>` after the pattern.
143173

0 commit comments

Comments
 (0)