gpt4 book ai didi

scala - Java SortedMap 到 Scala TreeMap

转载 作者:行者123 更新时间:2023-12-02 01:13:01 24 4
gpt4 key购买 nike

我在将 java SortedMap 转换为 scala TreeMap 时遇到问题。 SortedMap来自反序列化,在使用之前需要转换为scala结构。

出于好奇,一些背景是序列化结构是通过 XStream 编写的,并且在反序列化时我注册了一个转换器,它表示可以分配给 SortedMap[Comparable[_],_] 的任何内容应该给我。因此,我的 Convert 方法被调用,并被赋予一个可以安全地转换的 Object,因为我知道它的类型为 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)) })

最佳答案

首先,澄清您的错误:

// 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]]

但是,如果您确实不知道 key 的类型,我认为您无法根据 Comparable#compareTo 创建 Ordering,位于至少没有反射(reflection):

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)

关于scala - Java SortedMap 到 Scala TreeMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2163925/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com