Java 类似对象的惯用用法
我正在使用一些 java.util.Date (它实现了 java.lang.Comparable)并且希望能够很好地使用它,例如使用 <和 >= 而不是“compareTo(other) == 1”。有没有一种很好的方法可以轻松地混合像 scala.math.Ordered 这样的东西,而不需要大量的样板?
I'm using some java.util.Date (which implements java.lang.Comparable) and would like to be able to use it nicely, e.g. use < and >= instead of "compareTo(other) == 1". Is there a nice way to just easily mix in something like scala.math.Ordered without a lot of boiler plate?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Ordering 伴生对象中,存在从 Comparable[A] 到 Ordering[A] 的隐式转换。所以你可以这样做:
In the Ordering companion object there is an implicit conversion from Comparable[A] to Ordering[A]. So you can do this:
我知道这是一个老问题,但这里有一个稍微简单的解决方案,在提出问题时可能不可用。
任何实现 Comparable 的 Java 类型都应该与比较运算符无缝协作。例如,
I know this is an old question, but here's a slightly simpler solution that may not have been available when the question was asked.
Any Java types that implement
Comparable
should then work seamlessly with comparison operators. For example,在这种情况下,你不能混合使用
Ordered
,afaik...我尝试了一下,但遇到了困难,因为compareTo
在那里和java.lang 中都定义了.可比较
。编译器抱怨Ordered
在方法的定义中没有使用override
;我不知道如何解决这个问题。因此定义一个隐式的
Ordering[Date]
。您可以将此DateOrdering
对象放在任何地方(例如,在伴生对象中)。然后在您的代码中:
Ordering
对象包含一个隐式 def mkOrderingOps (lhs: T): Ops
。Ops
类包含<
。>=
等方法,并且此隐式 def 是 根据 Ordering 的类型参数(此处为任何Date
实例)来拉皮条我的库模式。You can't mix in
Ordered
in this case, afaik... I tried it and ran into difficulties becausecompareTo
is defined both there and injava.lang.Comparable
. The compiler complains thatOrdered
doesn't useoverride
in its definition of the method; I don't know how to get around that.So define an implicit
Ordering[Date]
. You can put thisDateOrdering
object anywhere (e.g. in companion object).Then in your code:
The
Ordering
object contains animplicit def mkOrderingOps (lhs: T): Ops
. TheOps
class contains the<
.>=
etc methods, and this implicit def is an example of the pimp my library pattern on whatever the type parameter of the Ordering is (here, anyDate
instance).