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

意外的Scala模式匹配语法

发布时间:2020-12-16 09:09:39 所属栏目:安全 来源:网络整理
导读:我有一个 Scala元组列表,如下所示: val l = List((1,2),(2,3),(3,4)) 我想将它映射到Int列表中,其中每个项目是相应元组中Ints的总和.我也不想使用x._1表示法,所以我用这样的模式匹配解决了问题 def addTuple(t: (Int,Int)) : Int = t match { case (first,s
我有一个 Scala元组列表,如下所示:

val l = List((1,2),(2,3),(3,4))

我想将它映射到Int列表中,其中每个项目是相应元组中Ints的总和.我也不想使用x._1表示法,所以我用这样的模式匹配解决了问题

def addTuple(t: (Int,Int)) : Int = t match { 
    case (first,second) => first + second 
}
var r = l map addTuple

这样做我按预期获得了列表r:List [Int] = List(3,5,7).在这一点上,几乎是偶然的,我发现我可以使用如下的缩写形式获得相同的结果:

val r = l map {case(first,second) => first + second}

我在我的文档中找不到对此语法的任何引用.这是正常的吗?我错过了一些微不足道的东西吗?

解决方法

请参见语言参考的第8.5节“模式匹配匿名函数”.

An anonymous function can be defined by a sequence of cases

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

which appear as an expression without a prior match. The expected type of such an expression must in part be defined. It must be either scala.Functionk[S1,...,Sk,R] for some k > 0,or scala.PartialFunction[S1,R],where the argument type(s) S1,Sk must be fully determined,but the result type R may be undetermined.

期望的类型deternines是否转换为FunctionN或PartialFunction.

scala> {case x => x}  
<console>:6: error: missing parameter type for expanded function ((x0$1) => x0$1 match {
  case (x @ _) => x
})
       {case x => x}
       ^

scala> {case x => x}: (Int => Int)
res1: (Int) => Int = <function1>

scala> {case x => x}: PartialFunction[Int,Int]
res2: PartialFunction[Int,Int] = <function1>

(编辑:李大同)

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

    推荐文章
      热点阅读