将对象转换为可比较的类型 [英] Cast objects to comparable type
问题描述
在斯卡拉.我有两个 Any 类型的对象.如果可能,我想将对象转换为正确的 Ordered 特征,然后将它们与 < 进行比较.方法.否则,我想抛出异常.应该很简单,但我很难过...
In Scala. I have two objects of type Any. If it's possible, I'd like to cast the objects to the correct Ordered trait, and then compare them with the < method. Otherwise, I want to throw an exception. Should be simple, but I'm stumped...
推荐答案
您可以使用 Ordering
类型类来实现:
You can implement this with Ordering
type class:
def compare[T : Ordering : Manifest](a: AnyRef, b: AnyRef) = {
val c = manifest[T].erasure
if (c.isAssignableFrom(a.getClass) && c.isAssignableFrom(b.getClass))
implicitly[Ordering[T]].compare(a.asInstanceOf[T], b.asInstanceOf[T])
else
throw new IllegalArgumentException("Wrong argument type")
}
然后像这样使用它:
compare[Date](new Date, new Date)
compare[String]("A", "B")
但是这段代码会抛出IllegalArgumentException
:
compare[Date]("A", "B")
更新
如果您确实不知道要比较的对象类型,则可以使用以下解决方案:
Update
If you really don't know types of objects, that you are trying to compare, then you can use this solution:
def compare(a: AnyRef, b: AnyRef) = {
val c = classOf[Comparable[_]]
if (c.isAssignableFrom(a.getClass) && c.isAssignableFrom(a.getClass) && a.getClass == b.getClass) {
a.asInstanceOf[Comparable[AnyRef]].compareTo(b.asInstanceOf[Comparable[AnyRef]])
} else {
throw new IllegalArgumentException("Incopatible argument types: " + a.getClass.getName + " and " + b.getClass.getName)
}
}
它归结为 Java 的 Comparable
接口.通常,scala 有 2 个特性用于此目的:
It falls down to Java's Comparable
interface. Generally scala has 2 traits for this purpose:
Ordred
- 类似于Comparable
,但现有类(如String
或Date
)没有实现它,所以你不能在运行时检查它(至少对于这些类)Ordering
- 它是类型类,您无法在运行时检索它.
Ordred
- similar toComparable
, but existing classes (likeString
orDate
) do not implement it, so you can't check it at runtime (at least for these classes)Ordering
- it's type class, and you can't retrieve it at runtime.
另一方面,Ordered
扩展了 Comparable
接口,因此该解决方案也适用于所有扩展 Ordered
的类.
From the other hand Ordered
extends Comparable
interface, so this solution should also work for all classes that extend Ordered
.
这篇关于将对象转换为可比较的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!