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 https://earldouglas.com/type-classes/eq.md |
  codedown scala | xargs -0 scala -nc -e
(6 * 7) === 42: true
(6 + 7) === 42: false