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

KAs*_*KAs 6 lambda scala

如果将map方法应用于Scala中的元组列表,则会出现如下错误:

scala> val s = List((1,2), (3,4))
s: List[(Int, Int)] = List((1,2), (3,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)
Run Code Online (Sandbox Code Playgroud)

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

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

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

谁知道它为什么?谢谢.

Yuv*_*kov 8

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

val s = List((1,2), (3,4))
val result = s.map { case (a, b) => a + b }
Run Code Online (Sandbox Code Playgroud)

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

val s = List((1,2), (3,4))
val result = s.map(x => x._1 + x._2)
Run Code Online (Sandbox Code Playgroud)

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