scalacompilation

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 the error:

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

why?


Solution

  • 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