Last active
August 29, 2015 14:28
-
-
Save frgomes/25354fc0aef57ea8c442 to your computer and use it in GitHub Desktop.
Scala - Generic way to convert data structures
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
http://stackoverflow.com/questions/3074118/how-do-i-convert-a-mapint-any-to-a-sortedmap-in-scala-or-a-treemap