Skip to content

Instantly share code, notes, and snippets.

@jamesyang124
Last active February 15, 2023 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jamesyang124/0780fb6dc567fef6faac92da469f8c71 to your computer and use it in GitHub Desktop.
Save jamesyang124/0780fb6dc567fef6faac92da469f8c71 to your computer and use it in GitHub Desktop.
Scala Collection Guide

Traversabel#flatten

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment