12

Groovy has the spaceship operator <=> which provides an easy way to implement comparisons. How can I chain it in a groovier way then the code below? In this example I want to compare the items by price first and then by name if both have the same price.


class Item implements Comparable {
  int price
  String name

  int compareTo(Item other) {
    int result = price <=> other.price
    if (result == 0) {
      result = name <=> other.name
    }
    return result
  }
}
raffian
  • 31,267
  • 26
  • 103
  • 174
Leonard Brünings
  • 12,408
  • 1
  • 46
  • 66

1 Answers1

33

Since the spaceship operator <=> returns 0 if both are equal and 0 is false according to Groovy Truth, you can use the elvis operator ?: to efficiently chain your sorting criteria.


class Item implements Comparable {
  int price
  String name

  int compareTo(Item other) {
    price <=> other.price ?: name <=> other.name
  }
}
Colin Harrington
  • 4,459
  • 2
  • 27
  • 32
Leonard Brünings
  • 12,408
  • 1
  • 46
  • 66