Eq is an alternative to the standard Java
It is defined by the single method
def eqv(x: A, y: A): Boolean
In Scala it’s possible to compare any two values using
== (which desugars to Java
This is because
equals type signature uses
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" // <console>:13: warning: comparing values of types Int and String using `==' will always yield false // 42 == "Hello" // ^ // error: No warnings can be incurred under -Xfatal-warnings.
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.
Eq syntax package also offers some handy symbolic operators:
import cats.implicits._ // import cats.implicits._ 1 === 1 // res2: Boolean = true "Hello" =!= "World" // res3: Boolean = true
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
The first option using
Eq.fromUniversalEquals only defers to
== and works like this:
import cats.kernel.Eq // import cats.kernel.Eq import cats.implicits._ // import cats.implicits._ case class Foo(a: Int, b: String) // defined class Foo implicit val eqFoo: Eq[Foo] = Eq.fromUniversalEquals // eqFoo: cats.kernel.Eq[Foo] = cats.kernel.Eq$$anon$107@383facbe Foo(10, "") === Foo(10, "") // res4: Boolean = true
For an example using Kittens check out the kittens repo.