2013-11-09 174 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))

相關問題