Ordering, a Scala language concept

Last updated

In Scala, the 'Ordering' type is a 'type class' that contains methods to determine an ordering of specific types.

assert(List(3, 2, 1).sorted == List(1, 2, 3))

assert(List(3, 2, 1).sorted(Ordering[Int].reverse) == List(3, 2, 1))

assert(Ordering[Int].lt(1, 2))

assert(!Ordering[Int].lt(2, 1))

Custom orderings can be created and composed

The 'Ordering' type class is very powerful because complex orderings can be achieved from small parts, and they can even be context-specific.

final case class Person(name: String, height: Int)

val people: List[Person] = List(
  Person("Ann", height = 176),
  Person("Thomas", height = 175),
  Person("Judy", height = 173)

implicit val personOrdering: Ordering[Person] =
  Ordering.by((_: Person).height)

assert(people.sorted.map(_.name) == List("Judy", "Thomas", "Ann"))

assert(people.sortBy(_.name).map(_.name) == List("Ann", "Judy", "Thomas"))

people.sortBy(person => (person.height, person.name))

To learn more about Type Classes go to: Type Class.