trait Eq[A] {
def eq(x: A, y: A): Boolean
}
object Eq {
implicit def anyEquals[A]: Eq[A] =
new Eq[A] {
def eq(x: A, y: A): Boolean =
== y
x }
implicit class EqOps[A: Eq](x: A) {
def ===(y: A): Boolean =
[Eq[A]].eq(x, y)
implicitly}
}
import Eq._
println(s"(6 * 7) === 42: ${(6 * 7) === 42}") // true
println(s"(6 + 7) === 42: ${(6 + 7) === 42}") // false
// println((6 * 7) === "42") // won't compile
This file is literate Scala, and can be run using Codedown:
$ curl https://earldouglas.com/posts/type-classes/eq.md |
codedown scala | xargs -0 scala -nc -e
(6 * 7) === 42: true
(6 + 7) === 42: false