6

链接匹配表达式无法编译。

val x = Array("abc", "pqr")

x match {
  case Array("abc", _*) => Some("abc is first")
  case Array("xyz", _*) => Some("xyz is first")
  case _ => None
} match {
  case Some(x) => x
  case _ => "Either empty or incorrect first entry"
}

虽然以下编译良好:

(x match {
  case Array("abc", _*) => Some("abc is first")
  case Array("xyz", _*) => Some("xyz is first")
  case _ => None
}) match {
  case Some(x) => x
  case _ => "Either empty or incorrect first entry"
}

为什么后面的版本(第一个匹配表达式在括号中)编译得很好,而早期的版本却没有?

4

1 回答 1

4

如果它被允许,你不能这样做:

scala> List(1,2,3) last match { case 3 => true }
warning: there were 1 feature warning(s); re-run with -feature for details
res6: Boolean = true

也就是说,如果它是中缀表示法,那么左边的东西就不可能是后缀。

不允许中缀匹配允许后缀审查。

该表达式以自然方式解析

(List(1,2,3) last) match { case 3 => true }

也就是说,如果后缀表示法是自然的而不是邪恶的。

功能警告适用于import language.postfixOps. 也许关闭该功能后,正义捍卫者会愿意招待import language.infixMatch

考虑与 的语法同级的结构match,如果没有括号就不能固定:

scala> if (true) 1 else 2 match { case 1 => false }
res4: AnyVal = 1   // not false

scala> (if (true) 1 else 2) match { case 1 => false }
res1: Boolean = false

或者

scala> throw new IllegalStateException match { case e => "ok" }
<console>:11: error: type mismatch;   // not "ok", or rather, Nothing
 found   : String("ok")
 required: Throwable
              throw new IllegalStateException match { case e => "ok" }
                                                                ^

scala> (throw new IllegalStateException) match { case e => "ok" }
java.lang.IllegalStateException
于 2013-08-09T23:03:49.267 回答