Skip to content

Instantly share code, notes, and snippets.

@sgalles
Last active August 29, 2015 13:57
Show Gist options
  • Save sgalles/9716953 to your computer and use it in GitHub Desktop.
Save sgalles/9716953 to your computer and use it in GitHub Desktop.
Ceylon class that mimic the new Comparator#comparing method from Java 8
"Create comparators a la Java 8 Comparator#comparing"
class Comparing<Element>(_comparator){
variable Comparison(Element,Element) _comparator;
shared Comparison(Element,Element) comparator => _comparator;
shared Comparing<Element> thenComparing(Comparison comparing(Element x, Element y)){
value currentComparator = comparator;
Comparison newComparator(Element x, Element y){
value comparison = currentComparator(x,y);
return comparison != equal then comparison else comparing(x,y);
}
_comparator = newComparator;
return this;
}
}
"Test it with a Person class"
class Person(shared String firstName, shared String lastName)
satisfies Comparable<Person>{
value comparator = Comparing(byIncreasing(Person.lastName))
.thenComparing(byIncreasing(Person.firstName))
.comparator;
shared actual Comparison compare(Person other) => comparator(this,other);
}
void run() {
assert(Person("Bob","B") > Person("Henry","A"));
assert(Person("Bob","A") < Person("Henry","A"));
assert(Person("Bob","A") <=> Person("Bob","A") == equal);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment