Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Scala matchers why Some(Some(1),1) can't match?

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?

like image 661
Bryan Hunt Avatar asked May 28 '11 22:05

Bryan Hunt


People also ask

How does pattern matching work in scala?

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.

How does pattern matching work?

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.

How do you write a match case in Scala?

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...") }

Which method of case class allows using objects in pattern matching?

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.


1 Answers

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.

like image 93
user unknown Avatar answered Sep 25 '22 23:09

user unknown