Pattern Match "return" value
pattern-matching, scala
Solution
Yes it should work, because (almost) everything in Scala is an expression and every expression can be used as a pattern match.
In this case the pattern match is an expression, so it can be used by another "chained" pattern match. But the compiler doesn't like it.
Giving the compiler a little hint with parentheses helps:
case class ADT(value: Int)
val a = ADT(5)
(a match {
case ADT(a) if a > 4 => ADT(a * 3)
case ADT(a) => ADT(a + 1)
}) match {
case ADT(a) if a > 13 => println(a)
case _ => {}
}
Problem
Why is it not possible to chain pattern matching constructs? For instance, the following is legal, if nonsensical, ``` val a = ADT(5) val b = a match { case ADT(a) if a > 4 => ADT(a * 3) case ADT(a) => ADT(a + 1) } b match { case ADT(a) if a > 13 => doSomething(a) case _ => {} } ``` but the following is not: ``` a match { case ADT(a) if a > 4 => ADT(a * 3) case ADT(a) => ADT(a + 1) } match { case ADT(a) if a > 13 => doSomething(a) case _ => {} } ``` I suspect it's because I shouldn't be doing it in the first place, but in principle I don't see why it's not legal.