Cats Core, Part 8: Order, and Why It Also Decides Equality
In Part 7 I replaced == with Cats' Eq, so that the compiler checks that both sides of a comparison have the same type. Eq answers one question: are these two values equal? Sorting, min, max and "which contract has the highest premium" need more than that. They need to know which value comes first. In Cats that is Order.
This time I used a new scratch sbt project: Scala 2.13.18 and cats-core 2.12.0, with one file, src/main/scala/stuff/Main.scala.
The file
package stuff
import cats.Order
import cats.implicits._
object Main extends App {
final case class Contract(id: String, premium: BigDecimal, startYear: Int)
object Contract {
implicit val byPremium: Order[Contract] = Order.by(_.premium)
}
val a = Contract("C1", 120, 2024)
val b = Contract("C2", 95, 2025)
println(a compare b)
println(a > b)
println(a min b)
println(List(a, b).maximumOption)
println(List(a, b).sorted(Contract.byPremium.toOrdering))
}Running it prints:
1
true
Contract(C2,95,2025)
Some(Contract(C1,120,2024))
List(Contract(C2,95,2025), Contract(C1,120,2024))I had written the expected output as comments next to each line before I ran the file. Two of them were wrong. I expected a min b to be the first contract, but min returns the whole value with the lower premium, which is C2. I removed the comments and used the real output, which I should have done from the start.
compare returns an Int: negative, zero or positive, as Java's Comparator does. > and min come from the Cats import, and maximumOption is the Foldable method that picks the largest element with the Order in scope.
Eq, PartialOrder, Order
Order is the last of three type classes in cats-kernel. Simplified, they are:
trait Eq[A] {
def eqv(x: A, y: A): Boolean
}
trait PartialOrder[A] extends Eq[A] {
def partialCompare(x: A, y: A): Double
}
trait Order[A] extends PartialOrder[A] {
def compare(x: A, y: A): Int
}Each type class extends the previous one. An Order is a PartialOrder, and a PartialOrder is an Eq. Order already implements eqv for you, as compare(x, y) == 0. That one line is the source of the main gotcha below.

Every Order is also an Eq, and Order derives its equality from compare.
When values cannot be compared
PartialOrder is for types where some pairs have no order. Sets ordered by "is a subset of" are the standard example: Set(1) is neither smaller nor larger than Set(2). Cats represents that with NaN:
val subset = PartialOrder[Set[Int]]
subset.partialCompare(Set(1), Set(1, 2)) // -1.0 Set(1) is a subset
subset.partialCompare(Set(1), Set(2)) // NaN neither contains the other
subset.tryCompare(Set(1), Set(2)) // NoneOrder cannot return that answer, because compare returns an Int. For premiums that is correct: every pair of BigDecimals has an order.
Gotcha: the ordering also decides equality
Since Order extends Eq, the ordering you define also decides equality. With Order.by(_.premium), two different contracts with the same premium count as ===:
val a = Contract("C1", 120, 2024)
val c = Contract("C3", 120, 2026) // different id, same premium
a == c // false: case-class equality compares every field
a === c // true: Order's eqv is compare(a, c) == 0, premium onlyThis is the same trade-off as Eq.by in Part 7, but it is easier to miss. When I wrote Order.by(_.premium) I was only thinking about sorting. I was not thinking that I had also defined equality. And because I put the instance in Contract's companion object, it applies everywhere Contract is used. A === anywhere in the code now ignores the id.
Two ways to avoid it. Order on something that identifies the contract, for example Order.by(c => (c.premium, c.id)). Or keep a premium-only ordering as a named value that you pass where you need it (List(a, b).maximumOption(byPremium)), and don't make it implicit.

Order.by(_.premium) makes premium the sort key and also the equality key. The standard library needs an Ordering, which you get with toOrdering.
Gotcha: .sorted wants an Ordering
The standard library's .sorted takes a scala.math.Ordering, not a Cats Order. You bridge them with .toOrdering, as the last line of my file does:
// with only import cats.syntax.all._ (or no Cats import at all)
List(a, b).sorted
// error: could not find implicit value for parameter ord: Ordering[Contract]
List(a, b).sorted(Contract.byPremium.toOrdering)
// List(Contract(C2,95,2025), Contract(C1,120,2024))There is one complication. My file imports cats.implicits._, and there a plain .sorted does compile. I tested four imports in scala-cli. With none, or with cats.syntax.all._, it fails. With cats.implicits._ or cats.instances.all._, it compiles. The reason is in cats-kernel's Order.scala:
trait OrderToOrderingConversion {
implicit def catsKernelOrderingForOrder[A](implicit ev: Order[A]): Ordering[A] = ...
}
object Order extends OrderFunctions[Order] with OrderToOrderingConversioncats.implicits._ includes the instance traits, and OrderInstances extends this conversion, so the import brings it into scope. cats.syntax.all._, the import I use in the rest of this series, contains only syntax.
The conversion is also defined in Order's companion object, so why doesn't the compiler find it there? Because the compiler is looking for an Ordering[Contract]. Implicit scope for that type means the companions of Ordering and Contract. Order's companion is not one of them. The compiler would only look in Order's companion when it searches for an Order[…]. So I keep the explicit .toOrdering: it works with any import.
Remember it as
Order is a Comparator that also decides equality. PartialOrder is allowed to answer "can't compare".
Recall check
I am learning Cats with spaced repetition, so I end with questions: one on today's material, plus reviews of earlier days. Try to answer before you scroll.
Today: you define
Order.by[Contract, String](_.id). Are two contracts with the same id but different premiums===? Why?Day 1 review: if you never import an
Order[Contract]instance, where does the Scala 2 compiler still look for one?
There is no 7-day review yet, because I'm only on day 4.
Answers
Yes. Order extends Eq, and its equality is
compare == 0, so only the id is compared.In the implicit scope: the companion objects of the types involved. Here that is
Contract's companion (where the example puts the instance) and Order's companion. This is also why the Order-to-Ordering conversion above is not found without an import: for anOrdering[Contract], Order's companion is not part of the implicit scope.
What I take away
Order adds a total
compareto Eq and gives you<,>,min,maxandmaximumOption.Order's
eqviscompare == 0. When you choose the fields to order by, you also choose the fields that equality compares.PartialOrder is for types where some pairs cannot be compared, and it reports those pairs as
NaN.Use
.toOrderingwhen standard-library code needs anOrdering. Don't rely on whichever import happens to bring in the conversion.