Return match value

Why is it impossible to create a pattern matching chain? For example, the following is legal, if it is meaningless,

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 not the following:

 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 this because I should not do this in the first place, but in principle I do not understand why it is not legal.

+7
source share
2 answers

Yes, it should work because (almost) everything in Scala is an expression, and each expression can be used as a pattern match.

In this case, a pattern match is an expression, so it can be used with another chained match. But he does not like the compiler.

Providing the compiler with a small hint of 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 _ => {} } 
+5
source

Your intuition is correct; this is not nonsense - usually you could chain infix operators this way without parentheses (as other users have suggested). Indeed, match used as the & mdash method and worked as an infix operator (left-associative by default) - so your alternative syntax would work. However, in Scala 2.5, match , a special language construct was made instead of a method. Unfortunately, I do not know why this was done, but here's why: match not an infix operator, despite the apparent one.

+3
source

All Articles