Skip to content

Instantly share code, notes, and snippets.

@luigip
Created September 22, 2012 04:00
Show Gist options
  • Save luigip/3765066 to your computer and use it in GitHub Desktop.
Save luigip/3765066 to your computer and use it in GitHub Desktop.
class Ord[T](val lessThan: (T, T) => Boolean)
class Compare[T](x: T)(implicit ord: Ord[T]) {
def < (that: T) = ord.lessThan(x, that)
def > (that: T) = ord.lessThan(that, x)
}
implicit def anyToCompare[T: Ord](x: T) = new Compare(x)
/////////
// Note: [T: Ord] is a "context bound" and means there is a T[Ord] in implicit scope
// Usage example: note Foo doesn't extend `Compare`, so can be any existing class
case class Foo(x: String)
implicit val ordFoo: Ord[Foo] = new Ord(_.x.length < _.x.length)
Foo("abc") < Foo("XY") //false
Foo("abc") > Foo("XY") //true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment