Java SortedMap for Scala TreeMap

I am having problems converting java SortedMap to scala TreeMap. SortedMap comes from deserialization and must be converted to a scala structure before use.

Some background for the curious is that the serialized structure is recorded via XStream and upon desalization I register a converter that says that I need to transfer everything that can be assigned to SortedMap[Comparable[_],_]. Therefore, my conversion method is called and assigned to it Object, which can be safely discarded, because I know its type SortedMap[Comparable[_],_]. Where it gets interesting. Here is an example of code that could explain it.

// a conversion from comparable to ordering
scala> implicit def comparable2ordering[A <: Comparable[A]](x: A): Ordering[A] = new Ordering[A] {
     |     def compare(x: A, y: A) = x.compareTo(y)
     |   }
comparable2ordering: [A <: java.lang.Comparable[A]](x: A)Ordering[A]

// jm is how I see the map in the converter. Just as an object. I know the key
// is of type Comparable[_]
scala> val jm : Object = new java.util.TreeMap[Comparable[_], String]()        
jm: java.lang.Object = {}

// It safe to cast as the converter only gets called for SortedMap[Comparable[_],_]
scala> val b = jm.asInstanceOf[java.util.SortedMap[Comparable[_],_]]
b: java.util.SortedMap[java.lang.Comparable[_], _] = {}

// Now I want to convert this to a tree map
scala> collection.immutable.TreeMap() ++ (for(k <- b.keySet) yield { (k, b.get(k))  })
<console>:15: error: diverging implicit expansion for type Ordering[A]
starting with method Tuple9 in object Ordering
       collection.immutable.TreeMap() ++ (for(k <- b.keySet) yield { (k, b.get(k))  })
+3
2

-, :

// The type inferencer can't guess what you mean, you need to provide type arguments.
// new collection.immutable.TreeMap  
// <console>:8: error: diverging implicit expansion for type Ordering[A]
//starting with method Tuple9 in object Ordering
//       new collection.immutable.TreeMap
//       ^

Comparable[T] Ordering[T] .

// This implicit only needs the type parameter.
implicit def comparable2ordering[A <: Comparable[A]]: Ordering[A] = new Ordering[A] {
   def compare(x: A, y: A) = x.compareTo(y)
}

trait T extends Comparable[T]

implicitly[Ordering[T]]

, , , Ordering Comparable#compareTo, , :

val comparableOrdering = new Ordering[AnyRef] {
  def compare(a: AnyRef, b: AnyRef) = {
    val m = classOf[Comparable[_]].getMethod("compareTo", classOf[Object])
    m.invoke(a, b).asInstanceOf[Int]
  }
}
new collection.immutable.TreeMap[AnyRef, AnyRef]()(comparableOrdering)
+2

, TreeMap. :

collection.immutable.TreeMap[whatever,whatever]() ++ ...

(, , , .)

0

Source: https://habr.com/ru/post/1730561/


All Articles