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

Scala中如何省略匹配字?

发布时间:2020-12-16 09:13:50 所属栏目:安全 来源:网络整理
导读:在斯卡拉,你可以做 list.filter { item = item match { case Some(foo) = foo.bar 0 }} 但是你也可以通过省略匹配来做更快的方式: list.filter { case Some(foo) = foo.bar 0} Scala如何支持?这是新的2.9吗我一直在寻找它,我可以弄清楚这是可能的.它只是Sc
在斯卡拉,你可以做

list.filter { item =>
    item match {
      case Some(foo) => foo.bar > 0
    }
}

但是你也可以通过省略匹配来做更快的方式:

list.filter {
  case Some(foo) => foo.bar > 0
}

Scala如何支持?这是新的2.9吗我一直在寻找它,我可以弄清楚这是可能的.它只是Scala编译器的一部分?

解决方法

language specification地址在8.5节.相关部分:

An anonymous function can be de?ned by a sequence of cases

{ case p1 => b1 ... case pn => bn }

If the expected type is scala.Functionk[S1,...,Sk,R],the expression is taken to
be equivalent to the anonymous function:

(x1 : S1,xk : Sk) => (x1,xk) match {
  case p1 => b1 ... case pn => bn
}

If the expected type is scala.PartialFunction[S,the expression is taken to
be equivalent to the following instance creation expression:

new scala.PartialFunction[S,T ] {
  def apply(x: S): T = x match {
    case p1 => b1 ... case pn => bn
  }
  def isDefinedAt(x: S): Boolean = {
    case p1 => true ... case pn => true
    case _ => false
  }
}

所以键入表达式作为PartialFunction或函数会影响表达式的编译方式.

还有特征部分函数[-A,B]扩展(A)?B,所以部分函数PartialFunction [A,B]也是函数[A,B].

(编辑:李大同)

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

    推荐文章
      热点阅读