Created
May 31, 2013 16:02
-
-
Save ryanlecompte/5686012 to your computer and use it in GitHub Desktop.
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
// Modified version of the example from http://hseeberger.github.io/blog/2013/05/31/implicits-unchained-type-safe-equality-part2/ that shows that you don't need to use implicit evidence parameters. | |
object TypeWiseBalancedEquality { | |
implicit class Equal[A](val left: A) { | |
def ===[B](right: B)(implicit equality: Equality[A, B]): Boolean = | |
equality.areEqual(left, right) | |
} | |
trait Equality[A, B] { | |
def areEqual(left: A, right: B): Boolean | |
} | |
object Equality extends LowPriorityEqualityImplicits { | |
implicit def rightSubtypeOfLeftEquality[A, B <: A]: Equality[A, B] = | |
new Equality[A, B] { | |
override def areEqual(left: A, right: B): Boolean = left == right | |
} | |
} | |
trait LowPriorityEqualityImplicits { | |
implicit def leftSubtypeOfRightEquality[B, A <: B]: Equality[A, B] = | |
new Equality[A, B] { | |
override def areEqual(left: A, right: B): Boolean = left == right | |
} | |
} | |
} | |
import TypeWiseBalancedEquality._ | |
println(Seq(1, 2, 3) === List(1, 2, 3)) | |
println(List(1, 2, 3) === Seq(1, 2, 3)) | |
println("a" === "a") | |
// println(1 === "haha") - fails, as expected | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment