0

这段代码:

1 until 3 flatMap (x => x + 1)

在工作表中导致此错误:

Multiple markers at this line
- type mismatch;  found   : Int(1)  required: String
- type mismatch;  found   : Int(1)  required: String
- type mismatch;  found   : x.type (with underlying type Int)  required: ?{def +(x$1: ? >: Int(1)): ?} Note that implicit conversions are not applicable because they are ambiguous:  both method int2long in object Int of type (x: Int)Long  and method int2float in object Int of type (x: Int)Float  are possible conversion functions from x.type to ?{def +(x$1: ? >: Int(1)): ?}
- type mismatch;  found   : x.type (with underlying type Int)  required: ?{def +(x$1: ? >: Int(1)): ?} Note that implicit conversions are not applicable because they are ambiguous:  both method int2long in object Int of type (x: Int)Long  and method int2float in object Int of type (x: Int)Float  are possible conversion functions from x.type to ?{def +(x$1: ? >: Int(1)): ?}

此代码按预期运行:1 until 3 flatMap (x => x + 1)

所有适用的集合都map应该适用于flatMap吗?

4

3 回答 3

1

我假设当你说:

此代码按预期运行:1 until 3 flatMap (x => x + 1)

你的意思是写1 until 3 map (x => x + 1)

带有 的版本可以map工作,因为map从 中获取一个函数A => B,并返回一个B(即 a List[B])的列表。

with 的版本flatMap不起作用,因为flatMap需要一个函数 fromA => List[B]然后返回一个List[B]. (更准确地说,它是一个,GenTraversableOnce[B]但在这种情况下您可以将其视为列表)您尝试应用于 flatMap 的函数不返回列表,因此它不适用于您尝试执行的操作。

从该错误消息中,很难看出这一点。一般来说,如果您不疯狂地尝试从语句中删除所有括号,我认为您会在此类语句中获得更清晰的错误消息。

于 2013-11-09T16:05:32.920 回答
1

flatMap 期望函数的结果是可遍历的

def flatMap[B](f: (A) ⇒ GenTraversableOnce[B]): IndexedSeq[B]

不是简单类型 ( x + 1 ) 稍后将所有结果加入单个序列。

工作示例:

scala> def f: (Int => List[Int]) = { x => List(x + 1) }
f: Int => List[Int]

scala> 1 until 3 flatMap ( f )
res6: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 3)
于 2013-11-09T16:05:41.347 回答
0

我认为 flatMap 的想法是,您传递的函数有一个列表(或“GenTraversableOnce”,我将非正式地称之为列表),因此 map 会产生一个列表列表。flatMap 将其展平为一个列表。

或者换句话说,我认为您的地图示例的等价物是 1 到 3 flatMap (x => List(x + 1))

于 2013-11-09T16:05:49.843 回答