Home > database >  Scala sortBy descending with Option key
Scala sortBy descending with Option key

Time:11-25

I have the following object:

class Registration(
    domain: _root_.scala.Predef.String = "",
    registeredAt: Option[com.google.protobuf.timestamp.Timestamp] = None
)

and I need to sort the items by registeredAt desc.

I tried:

registrations.sortBy(_.registeredAt)(ord.reverse)

implicit def ord: Ordering[Option[Timestamp]] = Ordering.by(_.seconds)

However, I get an error on _.seconds because registeredAt is Option.

I also tried:

implicit val timeStampOrdering = new Ordering[Option[Timestamp]] {
    override def compare(x: Option[Timestamp], y: Option[Timestamp]): Int = x.map(_.seconds) compareTo y.map(_.seconds)
  }

But here I have an error that on compareTo

How can I resolve it?

CodePudding user response:

It is probably simplest to just extract the seconds in the sortBy call and avoid the need for a new Ordering. Negate the number to sort in reverse:

registrations.sortBy(_.registeredAt.fold(0)(0 - _.seconds))

(or registeredAt.map(_.seconds).getOrElse(0))

CodePudding user response:

You can use just an implicit Ordering[Timestamp].

There is an implicit conversion in Ordering that will transform any Ordering[T] into Ordering[Option[T]]:

implicit def ord: Ordering[Timestamp] =
  Ordering.by(_. seconds)

implicitly[Ordering[Option[Timestamp]]] //we have this ordering

CodePudding user response:

You are trying to create an Ordering[Timestamp], when what you need is

implicit def ord: Ordering[Option[Timestamp]] = Ordering.by(_.map(_.seconds))
  • Related