Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Scala sortBy descending with Option key

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading