Scala 使用flatMap时,是什么导致此错误?

Scala 使用flatMap时,是什么导致此错误?,scala,Scala,此代码: 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 I

此代码:

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直到3平面图(x=>x+1)


所有适用于
map
的集合是否也适用于
flatMap

我假设当你说:

此代码的行为与预期一致:
1直到3平面图(x=>x+1)

你想写
1直到3映射(x=>x+1)

带有
map
的版本之所以有效,是因为
map
a=>B
获取一个函数,并返回
B
的列表(即
列表[B]

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


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

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)

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

或者换句话说,我认为与您的地图示例相当的是 1到3平面图(x=>列表(x+1))