2013-11-09 151 views
0

此代码:使用flatMap时会导致此错误的原因是什么?

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

回答

1

我假设当你说:

此代码的行为与预期:1 until 3 flatMap (x => x + 1)

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

版本与map作品,因为map需要一个功能从A => B,并返回一个B(即,一个List[B])的列表。

flatMap的版本不起作用,因为flatMap需要A => List[B]中的功能,然后返回List[B]。 (更确切地说,这是一个GenTraversableOnce[B],但在这种情况下,您可以像处理List一样处理它)。您试图应用于flatMap的函数不会返回List,因此它不适用于您正在尝试执行的操作。

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

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) 
0

我觉得flatMap的想法是,你传递给函数有一个列表(或“GenTraversableOnce”,我只是把它列表中,非正式的),结果,所以地图会产生一个列表清单。 flatMap将其平滑到一个列表中。

或者换句话说,我想你的地图示例的等效将是 1直至3 flatMap(X =>列表(x + 1))

相关问题