如何在 Scala 中定义排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9061141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:50:32  来源:igfitidea点击:

How to define an Ordering in Scala?

scalasortingscala-collections

提问by Ivan

Having val hm: HashMap[org.joda.time.DateTime, MyType]I am trying to get the first and the last DateTimeof the set by means of hm.keys.minand hm.keys.maxrespectively but the compiler says No implicit Ordering defined for org.joda.time.DateTime. How to define this ordering (both implicit and explicit options are interesting)?

val hm: HashMap[org.joda.time.DateTime, MyType]我想获得第一和最后DateTime借助一组hm.keys.min,并hm.keys.max分别但是编译器说No implicit Ordering defined for org.joda.time.DateTime。如何定义这种排序(隐式和显式选项都很有趣)?

回答by retronym

object Joda {
    implicit def dateTimeOrdering: Ordering[DateTime] = Ordering.fromLessThan(_ isBefore _)
}

// elsewhere
import Joda._
dateTimes.sorted

回答by Majki

To facilitate working with Joda DateTime in Scala, nscala-time was created: https://github.com/nscala-time/nscala-time

为了方便在 Scala 中使用 Joda DateTime,创建了 nscala-time:https: //github.com/nscala-time/nscala-time

After including it in your project with

将其包含在您的项目中后

libraryDependencies += "com.github.nscala-time" %% "nscala-time" % "1.8.0"

you can just import OrderingImplicits. Either all at once:

你可以只导入OrderingImplicits. 要么一次性:

import com.github.nscala_time.time.OrderingImplicits._

or a particular one:

或特定的:

import com.github.nscala_time.time.OrderingImplicits.DateTimeOrdering