2024-12-20

Eq Type Class

Notes
This article was translated by GPT-5.2-Codex. The original is here.

Eq

Eq is a type class representing types for which equality is defined.

Cats' Eq is defined as a trait with an eqv method.

1
trait Eq[@sp A] extends Any with Serializable { self =>
2
3
def eqv(x: A, y: A): Boolean
4
5
def neqv(x: A, y: A): Boolean = !eqv(x, y)
6
}

neqv is defined to return the opposite boolean of eqv. Therefore, to define an Eq instance for a type, you only need to implement eqv. However, Eq can be defined for most data types (those without uncomparable values such as lambdas), so you would need to implement an Eq instance for each type. That is quite tedious, so the official documentation introduces two methods.

One is to use Eq.fromUniversalEquals, which is implemented in the official docs. The other is to use a library called kittens that helps Cats. The code looks like this.

Loading code...

With kittens, derives Eq is enough. Since Scala 3 can do the equivalent of Haskell's deriving, that feature can automatically derive Eq instances.

When you define an Eq instance, you can use === and =!= as aliases for eqv and eqnv 1. These operators 2 are different from equals because both operands must be the same type. In Java-derived equals, the method argument is Any, so if you compare different types, the compiler will warn but still compile. In most cases, comparing different types is a bug. Therefore, writing code with === and =!= from the Eq type class makes it safer by turning such cases into compile errors.

Code using Eq can be found in EqTypeClassTest.

Eq syntax

https://github.com/typelevel/cats/blob/v2.12.0/core/src/main/scala/cats/syntax/eq.scala

Type ClassSyntaxDescription
Eq=== (eqv)Returns true if left and right are equal.
Eq=!= (eqnv)Returns true if left and right are not equal.

Footnotes

  1. Methods and operators available for type class instances are defined in the cats.syntax package.

  2. In Scala, operators are just method syntax sugar (ref: Operators | Scala Documentation).