具有地图功能的Scala Lambda函数 [英] Scala lambda function with map function
问题描述
我定义以下变量x
val x = Array((3,2), (4,5))
其类型为Array[(Int, Int)]
当我执行以下操作时:
x.map((a: Int, b: Int) => "(" + a + ", " + b + ")")
我收到以下错误:
console:28: error: type mismatch;
found : (Int, Int) => String
required: ((Int, Int)) => ?
x.map((a: Int, b: Int) => "(" + a + ", " + b + ")")
为什么期望第一个元素的类型为((Int, Int))
?
Why does it expect the type of the first element to be ((Int, Int))
?
推荐答案
(Int, Int) => ...
是具有两个参数的函数的类型,两个参数都是Int
(这是(a: Int, b: Int) => ...
始终给出的).
(Int, Int) => ...
is the type of a function with two arguments, both Int
(and that's what (a: Int, b: Int) => ...
will always give).
((Int, Int)) => ...
是带有一个(Int, Int)
自变量的函数的类型. Array
上的map
需要一个带有一个参数的函数,对于Array[(Int, Int)]
,此参数的类型必须为(Int, Int)
.
((Int, Int)) => ...
is the type of a function with one (Int, Int)
argument. map
on Array
needs a function with one argument and for Array[(Int, Int)]
the type of this argument must be (Int, Int)
.
所以您需要写
x.map(pair => "(" + pair._1 + ", " + pair._2 + ")")
其中pair
具有类型(Int, Int)
或
x.map { case (a, b) => "(" + a + ", " + b + ")" }
(使用模式匹配).请注意,在这种情况下,需要使用大括号.
(using pattern-matching). Note that in this case braces are required.
这篇关于具有地图功能的Scala Lambda函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!