2017-09-03 71 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

谢谢,这真的回答了我的问题! –