Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Scala 2.10 `to` to convert a List to a SortedMap

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?

like image 372
Ralph Avatar asked Apr 12 '13 14:04

Ralph


2 Answers

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 Seqs elements instead of the Seq itself as parameter.

like image 161
Chirlo Avatar answered Sep 21 '22 06:09

Chirlo


@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.

like image 43
Régis Jean-Gilles Avatar answered Sep 23 '22 06:09

Régis Jean-Gilles