Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
75 views
in Technique[技术] by (71.8m points)

java - Using Ordering on Instant

Is there Ordering which I can use to Order Instant?

I'm currently using the following Ordering:

MyRuleEngine(Equals).eval(Instant.now(), Instant.now().plusSeconds(1))(Ordering.by(_.toEpochMilli)) shouldBe false

But its might throw Exception (@throws ArithmeticException if numeric overflow occurs) - any other suggestings? I want to order based on the time-line position of the instants

Im using the following function:

 def eval[T](checkedValue: T, checkedWithValue: T)(ord: Ordering[T]) : Boolean 

I'm looking for a solution as follows:

MyRuleEngine(GreaterThan).eval("B", "A")(scala.math.Ordering.String) shouldBe true
MyRuleEngine(GreaterThan).eval(10, 0)(scala.math.Ordering.Int) shouldBe true
MyRuleEngine(Equals).eval(true, true)(scala.math.Ordering.Boolean) shouldBe true

Using 2.12.8

question from:https://stackoverflow.com/questions/65909648/using-ordering-on-instant

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Unlike Ordering[String] or Ordering[Int], Scala doesn't have an explicit val or object with Ordering[Instant]. Scala compiler generates one on demand when you implicitly request it by relying on the fact that Instant extends Comparable in Java.

If you want to use the Ordering[Instant] provided by Scala, you have to summon the implicit one and have the compiler generate it for you:

MyRuleEngine(rule).eval(instant1, instant2)(Ordering[Instant])

or

MyRuleEngine(rule).eval(instant1, instant2)(implicitly)

You may also manually create an Ordering[Instant] in the same way the compiler does:

MyRuleEngine(rule).eval(instant1, instant2)(Ordering.ordered(identity))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...