Pattern Match “return” value

廉价感情. 提交于 2020-01-21 11:03:51

问题


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.


回答1:


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 _ => {}
}



回答2:


Your intuition is correct; it's not nonsense—normally you would be able to chain infix operators in such a way, without parentheses (as other users have suggested). Indeed, match used to be implemented as a method—and worked as an infix operator (left-associative by default)—so your alternate syntax would have worked. However, in Scala 2.5, match was made a special language construct instead of a method. Unfortunately, I don't know why that was done, but that is the reason: match is not an infix operator, despite seeming so.



来源:https://stackoverflow.com/questions/16370500/pattern-match-return-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!