加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 为什么链接匹配表达式不能编译?

发布时间:2020-12-16 18:35:34 所属栏目:安全 来源:网络整理
导读:参见英文答案 Pattern Match “return” value????????????????????????????????????2个 链接匹配表达式无法编译. val x = Array("abc","pqr")x match { case Array("abc",_*) = Some("abc is first") case Array("xyz",_*) = Some("xyz is first") case _ =
参见英文答案 > Pattern Match “return” value????????????????????????????????????2个
链接匹配表达式无法编译.

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("xyz is first")
  case _ => None
}) match {
  case Some(x) => x
  case _ => "Either empty or incorrect first entry"
}

为什么后面的版本(第一个匹配表达式在paranthesis中)编译正常而前一个版本没有?

解决方法

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

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

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

禁止中缀匹配允许后缀scrutinee.

该表达式以自然方式解析

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

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

功能警告用于import language.postfixOps.也许关闭该功能,善良的捍卫者将愿意接受import language.infixMatch.

考虑要匹配的语法兄弟的构造,没有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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读