scala: list.flatten: no implicit argument matching parameter type (Any) = > Iterable[Any] was found
compiling this code in scala 2.7.6:
def flatten1(l: List[Any]): List[Any] = l.flatten
i get th开发者_如何学JAVAe error:
no implicit argument matching parameter type (Any) = > Iterable[Any] was found
why?
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 Int
s 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
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 Int
s, 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.
精彩评论