Scala模式匹配中中缀运算符的关联规则是什么

What's the associative rule of infix operator in Scala pattern match

我无法正确组织来描述真正的问题。但是我认为这些例子已经足够了:
这里有一些定义class和对象,

  case class ?(a: String, b: Int)
  case class MatchA(a: String, b: Int)

  object MatchInt {// can't
    def unapply(arg: Int): Option[(Long, Double)] = {
      Some(arg, arg)
    }
  }
  object & {// or :? or ?: or +& or +
    def unapply(arg: Int): Option[(Long, Double)] = {
      Some(arg, arg)
    }
  }

Example1,在 (b MatchInt c):

处带括号的中缀提取的正常用法
  @Test
  def matchOK1(): Unit = {
    MatchA("abc", 123) match {
      case a MatchA (b MatchInt c) =>
        println(s"$a, $b, $c")
    }

  }

示例 2,bc 中没有括号,但需要使用 &:??: 或 [=23 的特殊提取器名称定义=] 或 +,也许还有其他人。

  @Test
  def matchOK2(): Unit = {
    MatchA("abc", 123) match {
      case a MatchA b & c =>
        println(s"$a, $b, $c")
    }
  }

例子3,失败例子

  @Test
  def matchFail1(): Unit = {
    MatchA("abc", 123) match {
      case a MatchA b MatchInt c =>
        println(s"$a, $b, $c")
    }

  }

出现两个错误:

pattern type is incompatible with expected type;
[error]  found   : Int
[error]  required: Match.this.MatchA
[error]       case a MatchA b MatchInt c =>
[error]                       ^

constructor cannot be instantiated to expected type;
[error]  found   : Match.this.MatchA
[error]  required: Long
[error]       case a MatchA b MatchInt c =>
[error]              ^
[error] two errors found

此外,错误信息非常混乱。

Example4,错误信息与前者类似

 @Test
  def matchFail2(): Unit = {
    ?("abc", 123) match {
      case a ? b & c =>
        println(s"$a, $b, $c")
    }

  }

提取器名称下是否有特殊规则影响模式匹配?
非常感谢。

模式表达式的解析与普通表达式相同。

(在模式外,你得到 apply,在模式内,你得到 unapply。)

结合性和优先级的规则是in the spec

运算符的优先级高于 alnum 标识符。

这就是您的示例 2 有效的原因,但我猜您不喜欢这种语法。