Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two objects for equality in Scala?

I have a very basic equality check between two objects but it fails.

package foo
import org.junit.Assert._

object Sandbox extends App{
  class A

  val a = new A
  val b = new A
  assertEquals(a, b)

}

My use-case is more complex but I wanted to get my basics right. I get an assertion error when I run the code:

Caused by: java.lang.AssertionError: expected:<foo.Sandbox$A@3f86d38b> but was:<foo.Sandbox$A@206d63fd>
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.failNotEquals(Assert.java:743)
at org.junit.Assert.assertEquals(Assert.java:118)
at org.junit.Assert.assertEquals(Assert.java:144)
. . . . 

How can I compare two objects for equality?

like image 288
Core_Dumped Avatar asked Oct 30 '25 16:10

Core_Dumped


1 Answers

Unfortunately java defined an equals a hashCode and a toString method on every object. The default implementation of equals is to check referential equality, that is that they check that you are referring to the exact same object. Since you created two different objects, and gave no equals method to A they are not equal, since they aren't the same instance.

You can provide A with a better equals method, but anytime you override equals you should override hashCode as well to ensure that they two are in agreement. The rules for them being in agreement are:

  • if equals returns true, the two objects must return the same hashCode
  • if objects have different hashCodes, equals must return false.
like image 88
stew Avatar answered Nov 01 '25 12:11

stew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!