Search code examples
scalapattern-matchingcasescala-optionextractor

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?


Solution

  • 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.