Using Scala 2.10 `to` to convert a list to a sorted map

I am trying to convert pairs scala.collection.immutable.Listto scala.collection.immutable.SortedMapusing a new method tofrom 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 method to? Am I missing an intermediate method call?

+5
source share
2 answers

@gourlaysama already explained why it does not compile, and @Chirlo provide an easy (and recommended) to work: SortedMap( list: _*).

I would like to suggest 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 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 probably will not use it in production, given that doing is SortedMap( list: _* )not so difficult and does not require magic.

+7

:

SortedMap( list: _*)

, :

val map =  SortedMap( List((1, "Fred"), (2, "Barney")): _*)

_* , Seq Seq .

+9

All Articles