If a type class extend or transform to GenTraversableOnce
type, then it is flattenable. But you have to write your own GenTraversableOnce
rule
import scala.language.implicitConversions
implicit def int2Traversable[T <: Any](n: T): Traversable[Any] = n match {
case x: List[Any] => x
case c => Traversable[T](c)
}
List(5, List(6,7), List(7,8,List(9))).flatten
// List[Any] = List(5, 6, 7, 7, 8, List(9))
List(5, 6, 7, 7, 8, List(9)).flatten
// List[Any] = List(5, 6, 7, 7, 8, 9)
Above example have type inference issue, should define as not just List[Any]
type. Now consider the code snippets without injecting view implicit conversion:
List(5, List(6)).flatten
// No implicit view available from Any => scala.collection.GenTraversableOnce[B].
// List(5, List(6)).flatten
import scala.language.implicitConversions
implicit def int2Traversable[T <: Any](n: T) = Traversable[T](n)
List(5, List(6))
// res0: List[Any] = List(5, List(6))
Traversable[Option[A]]
will be flatten to Traversable[A]
, this avoid collect
with partial function boilerplate for Traversable[Option[A]]
types.
List(Some(6), None, None, Some(7)).flatten
// List(Some(6), Some(7))
http://stackoverflow.com/questions/1737452/how-to-flatten-a-list-of-different-types-in-scala
http://www.scala-lang.org/files/archive/spec/2.11/07-implicit-parameters-and-views.html