Created
September 22, 2012 04:00
-
-
Save luigip/3765066 to your computer and use it in GitHub Desktop.
This file contains 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
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