Equality Broken in Scala

Posted on November 1, 2017 by Marko Dimjašević

Scala is a programming language that heavily relies on the JVM platform. While there are many reasons to consider this to be an advantage for Scala, it also comes with many downsides given the language design choices. One big problem with Scala is equality, i.e., checking if values are equal.

I consider equality (the == operator) in Java broken because it compares objects, not values (Java is an object-oriented language) for their reference equality, i.e., if they are the same objects in memory. This is a big minus as it forces the programmer to think about low-level programming, which reference management is about. A brief and good demonstration of how equality is broken in Java is given in a blog post Problem of comparing wrapper objects with == operator.

Scala’s authors decided to inherit this brokenness from Java, which makes equality in Scala equally broken. For example, in Scala it is possible to compare an integer 1 to a string “abc”. There are some attempts to make equality in Scala less broken, but the problem won’t go away because of a requirement to maintain backward compatibility. In other words, there is a requirement to stay broken. As Odersky put it, “Scala prides itself of its strong static type system”, yet it cannot get value equality right.

Equality is a fundamental concept in programming. Equality is broken in Scala, which makes software engineering and development in it a painful undertaking. Scala allows for comparing apples and oranges, which is obviously ridiculous.

On the other hand, Haskell features a quite different type system. It seems to me that it brings sanity to programming when it comes to equality. In Haskell, equality is defined via a type class:

class Eq a where
  (==) :: a -> a -> Bool
  (/=) :: a -> a -> Bool

In other words, in Haskell you can test for equality of values of the same type only, i.e., an attempt to compare apples to oranges won’t compile. Therefore, with Haskell you have no funny attempts to fix equality with new operators such as === or even ====!

This is an obvious departure from what I wrote a year and a half earlier in a post titled I’m into Scala and in a post three years earlier, Going with JVM Languages.