我无法将 java SortedMap 转换为 scala TreeMap。SortedMap 来自反序列化,使用前需要转换成 scala 结构。
出于好奇,一些背景是序列化结构是通过 XStream 编写的,并且在反序列化时我注册了一个转换器,它说任何可以分配给我的东西都SortedMap[Comparable[_],_]
应该给我。所以我的 convert 方法被调用并被赋予了一个Object
我可以安全地转换的方法,因为我知道它是 type SortedMap[Comparable[_],_]
。这就是有趣的地方。这是一些可能有助于解释它的示例代码。
// 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's 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)) })