3
votes

Following along with chapters and examples in "Scala for the Impatient", there's an exercise related to using a Java TreeMap as a Scala SortedMap. In the scala shell, I tried this:

var t: scala.collection.SortedMap[String,Int] = new java.util.TreeMap[String,Int]()

but I get an error message about type mismatch. Is there a simple way to do this?

Note: I did an import of scala.collection.JavaConversions._ and then did this:

var t: SortedMap[String,Int] = TreeMap[String,Int]()

This works, but variable t has type java.util.SortedMap, not scala.collection.SortedMap.

2

2 Answers

2
votes

I haven't read that book, but you need to make your mind up. Is t a Scala SortedMap or is it a Java TreeMap?

A TreeMap isn't a SortedMap, so you can't assign one to a SortedMap variable without converting it. JavaConversions will do some conversions for you, including:

implicit def mapAsScalaMap [A, B] (m: Map[A, B]): Map[A, B]
   Implicitly converts a Java Map to a Scala mutable Map.

However there's nothing to convert to a SortedMap.

If this conversion seems mysterious to you, the library designers would agree, so JavaConversions is deprecated in Scala 2.10, in favour of JavaConverters, which requires a specific .asScala method to do a conversion.

Unfortunately JavaConverters doesn't have anything to produce a SortedMap either (.asScala gives you a mutable.Map). So you need to rebuild the collection using its elements.

import collection.JavaConverters._
import collection.SortedMap
var t: SortedMap[String, Int] =
    SortedMap[String, Int]() ++ new java.util.TreeMap[String,Int].asScala

Producing a new TreeMap in the code above is obviously a bit pointless because it's empty, but you should get the idea of how to deal with an existing one. If you don't have an existing one, just produce a new SortedMap in Scala.

1
votes
import collection._
import JavaConverters._

var t: scala.collection.SortedMap[String,Int] = 
    new java.util.TreeMap[String,Int]().asScala.map(identity)(breakOut)