scala

How to compare case class instances for inequality?


Say I have this case class:

case class TestCaseClass(a: Int, b: Int)

I want to be able to compare its instances for inequality (operators: <, >, <=, >=) field by field like so:

val a = TestCaseClass(1,1)
val b = TestCaseClass(1,2)
println(a < b) // should print "true"

Is there a library that does this?


Solution

  • In Scala 2.13+, the standard library has everything you need:

    // Needed to have < or > working if an implicit Ordering is in scope
    import scala.math.Ordered.orderingToOrdered
    
    case class TestCaseClass(a: Int, b: Int)
    
    // Ordering on a then b
    // More complex logic can be implemented 
    implicit val ord: Ordering[TestCaseClass] = 
      Ordering.by[TestCaseClass, Int](_.a)
        .orElse(Ordering.by[TestCaseClass,Int](_.b))
    
    val a = TestCaseClass(1,1)
    val b = TestCaseClass(1,2)
    println(a < b) // prints "true"
    

    If you're looking for a more generic definition for any case class as if it was a tuple, see stefanobaghino's answer.