Skip to content

Instantly share code, notes, and snippets.

@frgomes
Last active August 29, 2015 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frgomes/25354fc0aef57ea8c442 to your computer and use it in GitHub Desktop.
Save frgomes/25354fc0aef57ea8c442 to your computer and use it in GitHub Desktop.
Scala - Generic way to convert data structures
import collection.generic.CanBuildFrom
import collection.immutable.TreeMap
object test {
class TraversableW[A](t: Traversable[A]) {
def as[CC[X] <: Traversable[X]](implicit cbf: CanBuildFrom[Nothing, A, CC[A]]): CC[A] = t.map(identity)(collection.breakOut)
def to[Result](implicit cbf: CanBuildFrom[Nothing, A, Result]): Result = t.map(identity)(collection.breakOut)
}
implicit def ToTraverseableW[A](t: Traversable[A]): TraversableW[A] = new TraversableW[A](t)
List(1, 2, 3).as[Vector]
List(1, 2, 3).to[Vector[Int]]
List((1, 1), (2, 4), (3, 4)).to[Map[Int, Int]]
List((1, 1), (2, 4), (3, 4)).to[TreeMap[Int, Int]]
val tm: TreeMap[Int, Int] = List((1, 1), (2, 4), (3, 4)).to
("foo": Seq[Char]).as[Vector]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment