Scala 无法使用到可比较的隐式转换提供从DateTime到Ordered的隐式转换
我正在尝试将>=,>等与DateTime(joda)一起使用,而使其工作的唯一方法就是使用这种隐式转换Scala 无法使用到可比较的隐式转换提供从DateTime到Ordered的隐式转换,scala,Scala,我正在尝试将>=,>等与DateTime(joda)一起使用,而使其工作的唯一方法就是使用这种隐式转换 implicit def dateTime2ordered(x: DateTime): Ordered[DateTime] = new Ordered[DateTime] with Proxy { val self = x def compare(y: DateTime): Int = { x.compareTo(y) } } 我更喜欢一种更通用的形式,比如 impli
implicit def dateTime2ordered(x: DateTime): Ordered[DateTime] =
new Ordered[DateTime] with Proxy {
val self = x
def compare(y: DateTime): Int = {
x.compareTo(y)
}
}
我更喜欢一种更通用的形式,比如
implicit def comparable2ordered[A <: Comparable[A]](x: A): Ordered[A] =
new Ordered[A] with Proxy {
val self = x
def compare(y: A): Int = {
x.compareTo(y)
}
}
implicit def comparable2ordered[A很好,原始类型“Comparable”在Scala中被转换为“Comparable[\u]”
它们被称为存在主义类型,Compariable[_]是“compariable[T]for some{typet}”(自版本2.7起,请参见)
另请参见中的“存在类型”请参见,问题是,它已经存在。嗯,如果您查看对象有序
中的隐式转换,您会发现:
implicit def orderingToOrdered [T] (x: T)(implicit ord: Ordering[T]) : Ordered[T]
因此,只要有可用的Ordering[T]
,就可以生成Ordering[T]
。现在,要在Ordering
对象中查找Ordering[T]
:
implicit def ordered [A] (implicit arg0: (A) ⇒ Comparable[A]) : Ordering[A]
因此,如果您将具有可比[a]
的comparable:a传递给某个需要有序[a]
的对象,它将执行以下操作:
Ordered.orderingToOrdered(comparable)(Ordering.ordered(Predef.identity(comparable)))
现在,关于您的问题:使用存在类型是处理Java原始类型的正确方法。理论上,这可能会导致不正确的排序,但在实践中,这是极不可能的。但是,您可能会遇到隐式歧义问题,因为Scala已经有了Comparable=>Ordered
隐式转换,如上图所示。我偶然发现了这个问题,因为我也想使用关系运算符比较joda DateTime对象
Daniel的回答为我指明了正确的方向:scala.math.Ordered
中的隐式将A extensed java.lang.compariable[A]
的实例转换为Ordered[A]
-它们只需要被纳入范围。最简单的方法就是这样做(顺便说一句,我学到了)隐式地使用方法:
val aOrdering = implicitly[Ordering[A]]
import aOrdering._
需要注意的是,org.joda.time.DateTime
并没有扩展或实现Comparable
本身,它(间接)继承自org.joda.time.ReadableInstant
,它确实扩展了Comparable
。因此:
val dateTimeOrdering = implicitly[Ordering[DateTime]]
import dateTimeOrdering._
不会编译,因为DateTime
没有扩展compariable[DateTime]
。要在DateTime
上使用有序的关系运算符,必须执行以下操作:
val instantOrdering = implicitly[Ordering[ReadableInstant]]
import instantOrdering._
这是因为ReadableInstant
扩展了compariable[ReadableInstant]
,而Ordered
中的隐式转换可以将其转换为Ordered[ReadableInstant]
到目前为止还不错。但是,在某些情况下,有序的[ReadableInstant]
还不够好。(我遇到的是ScalaTest。)为了获得有序的[DateTime]
,我不得不这样做:
implicit object DateTimeOrdering extends Ordering[DateTime] {
def compare(d1: DateTime, d2: DateTime) = d1.compareTo(d2)
}
似乎应该有一个更简单的方法,但我想不出一个。我认为这是可行的:import com.github.nscala\u time.time.Imports.\u
是的,这是可行的,但只有在使用nscala时间库的情况下才行。;)我喜欢“扩展排序”解决方案:简洁明了,并将“魔力”保持在最低限度
implicit object DateTimeOrdering extends Ordering[DateTime] {
def compare(d1: DateTime, d2: DateTime) = d1.compareTo(d2)
}