scala: list.flatten: no implicit argument matching parameter type (Any) = > Iterable[Any] was found

别来无恙 提交于 2019-12-12 19:13:43

问题


compiling this code in scala 2.7.6:

def flatten1(l: List[Any]): List[Any] = l.flatten

i get the error:

no implicit argument matching parameter type (Any) = > Iterable[Any] was found

why?


回答1:


If you are expecting to be able to "flatten" List(1, 2, List(3,4), 5) into List(1, 2, 3, 4, 5), then you need something like:

implicit def any2iterable[A](a: A) : Iterable[A] = Some(a)

Along with:

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)

EDIT: the following was in my original answer until the OP clarified his question in a comment on Mitch's answer

What are you expecting to happen when you flatten a List[Int]? Are you expecting the function to sum the Ints in the List? If so, you should be looking at the new aggegation functions in 2.8.x:

val list = List(1, 2, 3)
println( list.sum ) //6



回答2:


The documentation:

Concatenate the elements of this list. The elements of this list should be a Iterables. Note: The compiler might not be able to infer the type parameter.

Pay close attention to that second sentence. Any cannot be converted to Iterable[Any]. You could have a list of Ints, and that list cannot be flattened since Int is not iterable. And think about it, if you have List[Int], what are you flattening? You need List[B <: Iterable[Any]], because then you would have two dimensions, which can be flattened to one.



来源:https://stackoverflow.com/questions/1598699/scala-list-flatten-no-implicit-argument-matching-parameter-type-any-iter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!