Home > other >  How do I sort by Ordering[Option[String]]?
How do I sort by Ordering[Option[String]]?

Time:10-31

val scoreSeq_opition: Seq[Option[String]] = List(Some("ngksf"),Some("fmgfdmg"),Some("mbmd"),None)
val nullOrdering: Ordering[Option[String]] = ????

I would like to sort by Ordering[Option[String]] if the above code. In that case, unlike the standard, we want None to be listed after Some, and Option[String] should be in the normal sort order for String. Last time we sorted strings in Score, but this time we are simply sorting strings of strings.

CodePudding user response:

For Option[String] it looks like this:

implicit val ord: Ordering[Option[String]] =
   Ordering.by(x => (x.isEmpty, x.getOrElse("")))

I am presuming that Score is just a type alias for Option[String] otherwise you need to create an Ordering[Score] with the appropriate rules. In that case the ordering can be in the companion object where the compiler will find it if it needs it.

  • Related