I am trying to convert a scala.collection.immutable.List
of pairs to a scala.collection.immutable.SortedMap
using the new to
method from Scala 2.10, but I get a compile-time error:
scala> List((1, "Fred"), (2, "Barney")).to[scala.collection.immutable.SortedMap]
<console>:10: error: scala.collection.immutable.SortedMap takes two type parameters, expected: one
List((1, "Fred"), (2, "Barney")).to[SortedMap]
^
Can this be done using the to
method? Am I missing an intermediate method call?
I had a similar question some time ago and came up with this:
SortedMap( list: _*)
So you can do it like :
val map = SortedMap( List((1, "Fred"), (2, "Barney")): _*)
The _*
means you take the Seq
s elements instead of the Seq
itself as parameter.
@gourlaysama already explained why it does not compile, and @Chirlo provided the simplest (and recommended) work around: SortedMap( list: _*)
.
I'd like to propose an alternative:
import collection.Traversable
import collection.generic.CanBuildFrom
implicit class RichPairTraversable[A,B]( t: Traversable[(A,B)] ) {
def toPairCol[Col[A,B]](implicit cbf: CanBuildFrom[Nothing, (A,B), Col[A, B]]): Col[A, B] = {
val b = cbf()
b.sizeHint(t)
b ++= t
b.result
}
}
Some test in the REPL:
scala> List((1, "Fred"), (2, "Barney")).toPairCol[scala.collection.immutable.SortedMap]
res0: scala.collection.immutable.SortedMap[Int,String] = Map(1 -> Fred, 2 -> Barney)
scala> List((1, "Fred"), (2, "Barney")).toPairCol[scala.collection.immutable.HashMap]
res1: scala.collection.immutable.HashMap[Int,String] = Map(1 -> Fred, 2 -> Barney)
Now, I will probably not use it in production, given that doing SortedMap( list: _* )
is not that
hard and requires no magic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With