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

时间:2018-01-26 05:12:51

标签: scala pattern-matching infix-operator

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

  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)
    }
  }

例1,中缀提取物的正常用法,括号为(b MatchInt c)

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

  }

示例2,bc中没有括号,但需要&:??:+&的特殊提取名称定义或+,也许是其他人。

  @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

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

例4,错误信息与前者类似

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

  }

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

1 个答案:

答案 0 :(得分:0)

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

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

关联性和优先级的规则是in the spec

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

这就是为什么你的示例2有效,但我想你不喜欢这种语法。