Notes
Eq
Eq is a type class representing types for which equality is defined.
- Eq
- Eq - cats-docs_2.13 2.12.0 javadoc
- cats/kernel/src/main/scala/cats/kernel/Eq.scala at v2.12.0 · typelevel/cats
Cats' Eq is defined as a trait with an eqv method.
1trait Eq[@sp A] extends Any with Serializable { self =>23def eqv(x: A, y: A): Boolean45def 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.
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 Class | Syntax | Description |
|---|---|---|
Eq | === (eqv) | Returns true if left and right are equal. |
Eq | =!= (eqnv) | Returns true if left and right are not equal. |
Footnotes
-
Methods and operators available for type class instances are defined in the
cats.syntaxpackage. ↩ -
In Scala, operators are just method syntax sugar (ref: Operators | Scala Documentation). ↩