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
1.7k views
in Technique[技术] by (71.8m points)

scala - How make implicit Ordered on java.time.LocalDate

I want to use java.time.LocalDate and java.time.LocalDateTime with an implicit Ordered like:

val date1 = java.time.LocalDate.of(2000, 1, 1)
val date2 = java.time.LocalDate.of(2010, 10, 10)
if (date1 < date2) ...

import scala.math.Ordering.Implicits._ doesn't work, because LocalDate inherits from Comparable<ChronoLocalDate> instead of Comparable<LocalDate>. How can I write my own imlicit Orderd to use <, <=, >, >= operators/methods to compare LocalDate's?

Edit:

I found a way with use of an implicit class:

import java.time.{LocalDate}

object MyDateTimeUtils {
  implicit class MyLocalDateImprovements(val ld: LocalDate)
           extends Ordered[LocalDate] {
    def compare(that: LocalDate): Int = ld.compareTo(that)
  }
}

// Test

import MyDateTimeUtils._

val d1 = LocalDate.of(2016, 1, 1)
val d2 = LocalDate.of(2017, 2, 3)

if (d1 < d2) println("d1 is less than d2")

But I would prefer a way like Scala is doing for all Java classes which implements Comparable<T>. You just have to import scala.math.Ordering.Implicits._ in your code. Scala implements it like:

implicit def ordered[A <% Comparable[A]]: Ordering[A] = new Ordering[A] {
  def compare(x: A, y: A): Int = x compareTo y
}

But unfortunately LocalDate implements Comparable<ChronoLocalDate> instead of Comparable<LocalDate>. I couldn't find a way to modify the above implicit ordered method to fit with LocalDate/Comparable<ChronoLocalDate>. Any idea?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can use Ordering.by to create ordering for any type, given a function from that type to something that already has an Ordering - in this case, to Long:

implicit val localDateOrdering: Ordering[LocalDate] = Ordering.by(_.toEpochDay)

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

...