如何在 Scala 中将 DateTimeComparator 转换为 Ordering[DateTime]
我刚刚输入了这个看起来有点难看的内容:
val maxTime = times.max(DateTimeComparator.getInstance().asInstanceOf[Comparator[DateTime]] asScala)
times
是 org.joda.time.DateTime 的序列。
必须有更好的方法来获取 DateTime 的 Ordering 对象。有没有?
特别是失去 asInstanceOf 会很棒......
I just typed this which seems a little ugly:
val maxTime = times.max(DateTimeComparator.getInstance().asInstanceOf[Comparator[DateTime]] asScala)
times
is a sequence of org.joda.time.DateTime.
There must be a better way to get that Ordering object for DateTime. Is there?
In particular it'd be great to lose the asInstanceOf ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
另一种可能性是使用
comparatorToOrdering
:我想这就是
asScala
调用的作用。我知道它并不漂亮:-|(不幸的是,需要进行强制转换,因为
DateTimeComparator
将Comparator
实现为原始类型。)Another possibility is to use
comparatorToOrdering
:I suppose that's what the
asScala
call does. It's not prettier, I know :-|(The cast is unfortunately required because
DateTimeComparator
implementsComparator
as a raw type.)您还可以编写自己的类来扩展 Ordering 特征,并将其用作最大值函数的输入:
You can also write your own class that extends the Ordering trait, and use this as input to the maximum function:
这也太丑了!
你的
asScala
来自哪里?其他想法
我不确定是否有更好的方法。
DateComparator
实现Comparator。max
方法需要一个Ordering[DateTime]
。 Ordered 和 Ordering 在 Scala 中是不变的。所以我认为这种情况下有必要使用asScala
。which is ugly too!
Where does your
asScala
come from?additional thoughts
I'm not sure there is a better way.
DateComparator
implements Comparator.the
max
method expects anOrdering[DateTime]
. Ordered and Ordering are invariant in Scala. So I think the case is necessary to useasScala
.最好的可能性,但有额外的依赖: NScala-Time 包装器 for Joda DateTime 隐含了 DateTimeOrdering:
https://github.com/nscala-time/nscala-time/blob/master/src/main/scala/com/github/nscala_time/time/Implicits.scala
Best possibility, but with additional dependency: NScala-Time wrapper for Joda DateTime has DateTimeOrdering implicit:
https://github.com/nscala-time/nscala-time/blob/master/src/main/scala/com/github/nscala_time/time/Implicits.scala
如果您愿意使用 Saddle,那里定义了隐式日期时间排序,在这种情况下,这足以解决问题:
In case you are willing to use Saddle, there's an implicit Datetime ordering defined there, in which case this is enough to solve the issue: