链接匹配表达式无法编译。
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"
}
为什么后面的版本(第一个匹配表达式在paranthesis中)编译正常而前一个版本没有编译?
答案 0 :(得分:3)
如果允许,你就不能这样做:
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
的语法兄弟,这些构造在没有parens的情况下是不可混合的:
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