Eq

API Documentation: Eq

Eq is an alternative to the standard Java equals method. It is defined by the single method eqv:

def eqv(x: A, y: A): Boolean

In Scala it's possible to compare any two values using == (which desugars to Java equals). This is because equals type signature uses Any (Java's Object) to compare two values. This means that we can compare two completely unrelated types without getting a compiler error. The Scala compiler may warn us in some cases, but not all, which can lead to some weird bugs. For example this code will raise a warning at compile time:

42 == "Hello"
//

While this code will compile without a hitch:

"Hello" == 42
// res1: Boolean = false

Ideally, Scala shouldn't let us compare two types that can never be equal.

As you can probably see in the type signature of eqv, it is impossible to compare two values of different types, eliminating these types of bugs altogether.

The Eq syntax package also offers some handy symbolic operators:

import cats.syntax.all._

1 === 1
// res2: Boolean = true

"Hello" =!= "World"
// res3: Boolean = true

Implementing Eq instances yourself for every data type might seem like huge drawback compared to only slight gains of typesafety. Fortunately for us, we have two great options. One option is to use inbuilt helper functions. Another option is to use a small library called kittens, which can derive a lot of type class instances for our data types including Eq.

The first option using Eq.fromUniversalEquals only defers to == and works like this:

import cats.kernel.Eq
import cats.syntax.all._


case class Foo(a: Int, b: String)


implicit val eqFoo: Eq[Foo] = Eq.fromUniversalEquals
// eqFoo: Eq[Foo] = cats.kernel.Eq$$anonfun$fromUniversalEquals$2@d0024f0


Foo(10, "") === Foo(10, "")
// res4: Boolean = true

For an example using Kittens check out the kittens repo.