File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change @@ -168,6 +168,39 @@ input match
168
168
169
169
In this example, name and age extract parts of the string based on the pattern. This is helpful for parsing structured text.
170
170
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
+
171
204
## Pattern guards
172
205
Pattern guards are boolean expressions which are used to make cases more specific. Just add ` if <boolean expression> ` after the pattern.
173
206
You can’t perform that action at this time.
0 commit comments