How make implicit Ordered on java.time.LocalDate

前端 未结 5 766
故里飘歌
故里飘歌 2021-01-04 00:33

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

val date1 = java.time.Loc         


        
5条回答
  •  一个人的身影
    2021-01-04 01:14

    Here is the solution that I use:

    define two implicits. The first one for making an Ordering[LocalDate] available. And a second one for giving LocalDate a compare method which comes in very handy. I typically put these in package objects in a library I can just include where I need them.

    package object net.fosdal.oslo.odatetime {
    
      implicit val orderingLocalDate: Ordering[LocalDate] = Ordering.by(d => (d.getYear, d.getDayOfYear))
    
      implicit class LocalDateOps(private val localDate: LocalDate) extends AnyVal with Ordered[LocalDate] {
        override def compare(that: LocalDate): Int = Ordering[LocalDate].compare(localDate, that)
      }
    }
    

    with both of these defined you can now do things like:

    import net.fosdal.oslo.odatetime._
    
    val bool: Boolean = localDate1 < localDate1
    
    val localDates: Seq[LocalDate] = ...
    val sortedSeq = localDates.sorted
    

    Alternatively... you could just use my library (v0.4.3) directly. see: https://github.com/sfosdal/oslo

提交回复
热议问题