Eq

Implementation

trait Eq[A] {
  def eq(x: A, y: A): Boolean
}

Extension methods

object Eq {

  implicit def anyEquals[A]: Eq[A] =
    new Eq[A] {
      def eq(x: A, y: A): Boolean =
        x == y
    }

  implicit class EqOps[A: Eq](x: A) {
    def ===(y: A): Boolean =
      implicitly[Eq[A]].eq(x, y)
  }
}

Example

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

Demo

This file is literate Scala, and can be run using Codedown:

$ curl -s https://earldouglas.com/posts/type-classes/eq.md |
  codedown scala | xargs -0 scala -nc -e
(6 * 7) === 42: true
(6 + 7) === 42: false