What's the difference between == and .equals in Scala?

You normally use ==, it routes to equals, except that it treats nulls properly. Reference equality (rarely used) is eq.


== is a final method, and calls .equals, which is not final.

This is radically different than Java, where == is an operator rather than a method and strictly compares reference equality for objects.


TL;DR

  • Override equals method to compare content of each instance. This is the same equals method used in Java
  • Use == operator to compare, without worrying about null references
  • Use eq method to check if both arguments are EXACTLY the same reference. Recommended not to use unless you understand how this works and often equals will work for what you need instead. And make sure to only use this with AnyRef arguments, not just Any

NOTE: On the case of equals, just as in Java, it may not return the same result if you switch the arguments eg 1.equals(BigInt(1)) will return false where the inverse will return true. This is because of each implementation checking only specific types. Primitive numbers dont check if the second argument is of Number nor BigInt types but only of other primitive types

Details

The AnyRef.equals(Any) method is the one overridden by subclasses. A method from the Java Specification that has come over to Scala too. If used on an unboxed instance, it is boxed to call this (though hidden in Scala; more obvious in Java with int->Integer). The default implementation merely compares references (as in Java)

The Any.==(Any) method compares two objects and allows either argument to be null (as if calling a static method with two instances). It compares if both are null, then it calls the equals(Any) method on boxed instance.

The AnyRef.eq(AnyRef) method compares only references, that is where the instance is located in memory. There is no implicit boxing for this method.

Examples

  • 1 equals 2 will return false, as it redirects to Integer.equals(...)
  • 1 == 2 will return false, as it redirects to Integer.equals(...)
  • 1 eq 2 will not compile, as it requires both arguments to be of type AnyRef
  • new ArrayList() equals new ArrayList() will return true, as it checks the content
  • new ArrayList() == new ArrayList() will return true, as it redirects to equals(...)
  • new ArrayList() eq new ArrayList() will return false, as both arguments are different instances
  • foo equals foo will return true, unless foo is null, then will throw a NullPointerException
  • foo == foo will return true, even if foo is null
  • foo eq foo will return true, since both arguments link to the same reference