Last active
December 25, 2018 21:41
-
-
Save jm-g/767f804b10667ca287e8a8c21a298525 to your computer and use it in GitHub Desktop.
Scala Ordering Helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 _) | |
implicit class OrderingOps[T]( val 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
Taken from: https://stackoverflow.com/questions/14695833/scala-idiom-for-ordering-by-multiple-criteria