It seems that nested matching doesn't work, which is a strange limitation.
An example of the behaviour follows:
Some(Some(1),2) match {
| case Some(Some(a),b) => a
| case e => e
| }
<console>:9: error: wrong number of arguments for <none>: (x: (Some[Int], Int))Some[(Some[Int], Int)]
case Some(Some(a),b) => a
^
<console>:9: error: not found: value a
case Some(Some(a),b) => a
^
This works:
Some(Some(1),2) match {
case Some(a) => a match {
case (Some(a),b) => "yay"
case e => "nay"
}
}
Now, am I just being a twit or is there a better way to achieve this?
Pattern matching is a mechanism for checking a value against a pattern. A successful match can also deconstruct a value into its constituent parts. It is a more powerful version of the switch statement in Java and it can likewise be used in place of a series of if/else statements.
Pattern Matching works by "reading" through text strings to match patterns that are defined using Pattern Matching Expressions, also known as Regular Expressions. Pattern Matching can be used in Identification as well as in Pre-Classification Processing, Page Processing, or Storage Processing.
Using if expressions in case statements i match { case a if 0 to 9 contains a => println("0-9 range: " + a) case b if 10 to 19 contains b => println("10-19 range: " + a) case c if 20 to 29 contains c => println("20-29 range: " + a) case _ => println("Hmmm...") }
The match method takes a number of cases as an argument. Each alternative takes a pattern and one or more expressions that will be performed if the pattern matches.
What is Some (Some(1),2)? An Option of Tuple of (Option (of Int) and Int)? This works:
scala> Some ((Some (1), 2)) match {
| case Some ((Some (a), b)) => a
| case e => e }
res13: Any = 1
Note the additional parenthesis around the tuple - it's a common mistake to have too few of them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With