Skip to content

Instantly share code, notes, and snippets.

@frgomes
Last active June 14, 2016 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frgomes/99bbd36b39488cbd6237 to your computer and use it in GitHub Desktop.
Save frgomes/99bbd36b39488cbd6237 to your computer and use it in GitHub Desktop.
Scala - Custom ordering
case class Employee(id: Int, firstName: String, lastName: String)
object Employee {
// Note that because `Ordering[A]` is not contravariant, the declaration
// must be type-parametrized in the event that you want the implicit
// ordering to apply to subclasses of `Employee`.
implicit def orderingByName[A <: Employee]: Ordering[A] =
Ordering.by(e => (e.lastName, e.firstName))
val orderingById: Ordering[Employee] = Ordering.by(e => e.id)
}
@frgomes
Copy link
Author

frgomes commented Jun 14, 2016

Pending review:

final class CompositeOrdering[T](val ord1: Ordering[T], val ord2: Ordering[T]) extends Ordering[T] {
  def compare(x: T, y: T) = {
    val comp = ord1.compare(x, y)
    if (comp != 0) comp else ord2.compare(x, y)
  }
}
object CompositeOrdering {
  def apply[T](orderings: Ordering[T] *) = orderings reduceLeft (_ orElse _)
}
trait OrderingOps {
   implicit class OrderingOps[T](ord: Ordering[T]) extends AnyVal {
    def orElse(ord2: Ordering[T]) = new CompositeOrdering[T](ord, ord2)
  }    
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment