2017-09-03 73 views
0

請按照下面的代碼。與斯卡拉混淆flatMap,地圖和拼合

import scala.collection.immutable.HashMap 

def myFunc(map : HashMap[Char,List[MyObject]], text : List[Char]) : List[MyObject] = { 

    text.flatMap(ch => map.get(ch))   //Gives compilation error 
    text.map(ch => map.get(ch)).flatten  //gives compilation error 
    text.flatMap(ch => map.get(ch)).flatten //This works 
} 

我不明白爲什麼前兩種方法不起作用?

編輯
我得到這個錯誤在第2行

Expression List[List[MyObject]] doesn't confirm to expected type list List[MyObject] 
+0

什麼是錯誤?它是「純粹的表達式在不確定的情況下使用」或類似的東西? – Carcigenicate

+0

@Carcigenicate我編輯了錯誤的問題 – Ashwin

+0

@pedromss我編輯了錯誤的問題 – Ashwin

回答

3

我認爲這裏的混亂與HashMap.get()功能。 get函數返回Option[List[MyObject]]。這就是爲什麼當你把它弄平時(就像在第三個例子中一樣),它會刪除選項。

Read more on Scala Options here.

+0

謝謝,這真的回答了我的問題! –