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

应用于scala中的元组列表时出现映射错误

发布时间:2020-12-16 18:53:40 所属栏目:安全 来源:网络整理
导读:如果将map方法应用于 Scala中的元组列表,则会出现如下错误: scala val s = List((1,2),(3,4))s: List[(Int,Int)] = List((1,4))scala s.map((a,b) = a+b)console:13: error: missing parameter typeNote: The expected type requires a one-argument functi
如果将map方法应用于 Scala中的元组列表,则会出现如下错误:

scala> val s = List((1,2),(3,4))
s: List[(Int,Int)] = List((1,4))

scala> s.map((a,b) => a+b)
<console>:13: error: missing parameter type
Note: The expected type requires a one-argument function accepting a 2-Tuple.
    Consider a pattern matching anonymous function,`{ case (a,b) =>  ... }`
    s.map((a,b) => a+b)
            ^
<console>:13: error: missing parameter type
    s.map((a,b) => a+b)

但是,如果我将类似的map方法应用于Int列表,它可以正常工作:

scala> val t = List(1,2,3)
t: List[Int] = List(1,3)

scala> t.map(a => a+1)
res14: List[Int] = List(2,3,4)

谁知道它为什么?谢谢.

解决方法

Scala不会自动解构元组.你需要使用大括号:

val s = List((1,4))
val result = s.map { case (a,b) => a + b }

或者使用类型为tuple的单个参数:

val s = List((1,4))
val result = s.map(x => x._1 + x._2)

Dotty(未来的Scala编译器)将自动解构元组.

(编辑:李大同)

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

    推荐文章
      热点阅读