Skip to content

Instantly share code, notes, and snippets.

@retronym
Created June 19, 2010 12:38
Show Gist options
  • Save retronym/444862 to your computer and use it in GitHub Desktop.
Save retronym/444862 to your computer and use it in GitHub Desktop.
Simple conversions between Scala collections
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
}
test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment