将对象转换为可比较的类型 [英] Cast objects to comparable type

查看:46
本文介绍了将对象转换为可比较的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在斯卡拉.我有两个 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,但现有类(如 StringDate)没有实现它,所以你不能在运行时检查它(至少对于这些类)
  • Ordering - 它是类型类,您无法在运行时检索它.
  • Ordred - similar to Comparable, but existing classes (like String or Date) 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆