scala:list.flatten:没有隐式参数匹配参数类型(Any)=>找到了Iterable [Any]

Itt*_*ayD 2 scala compilation

在scala 2.7.6中编译此代码:

def flatten1(l: List[Any]): List[Any] = l.flatten
Run Code Online (Sandbox Code Playgroud)

我收到错误:

no implicit argument matching parameter type (Any) = > Iterable[Any] was found
Run Code Online (Sandbox Code Playgroud)

为什么?

oxb*_*kes 6

如果你是期待能够"扁平化" List(1, 2, List(3,4), 5)List(1, 2, 3, 4, 5),那么你就需要这样的:

implicit def any2iterable[A](a: A) : Iterable[A] = Some(a)
Run Code Online (Sandbox Code Playgroud)

随着:

val list: List[Iterable[Int]] = List(1, 2, List(3,4), 5) // providing type of list 
                                                         // causes implicit 
                                                         // conversion to be invoked

println(list.flatten( itr => itr )) // List(1, 2, 3, 4, 5)
Run Code Online (Sandbox Code Playgroud)

编辑:以下是我的原始答案,直到OP在对米奇的答案的评论中澄清了他的问题

什么是你期待发生,当你flatten一个List[Int]?你期望函数总结Ints中的s List吗?如果是这样,你应该在2.8.x中查看新的aggegation函数:

val list = List(1, 2, 3)
println( list.sum ) //6
Run Code Online (Sandbox Code Playgroud)