Scala class and case class == comparison

peter picture peter · Feb 28, 2014 · Viewed 24.4k times · Source

I don't quite understand why when we compare two instance with the same properties of a class without overriding the equals method that it will give a false. But it will give a true when we compare two instances of a case class. For example

 class A(val name: String, val id: Int)
 case class B(name: String, id: Int)

 object Test {
    val a1 = new A('a',1)
    val a2 = new A('a',1)
    println(a1 == a2)   //this returns false

    var b1 = B('b',1)
    var b2 = B('b',1)
    println(b1 == b2)   //this returns true

 }

Could someone explain why, please?

Answer

wheaties picture wheaties · Feb 28, 2014

A case class implements the equals method for you while a class does not. Hence, when you compare two objects implemented as a class, instead of case class, what you're comparing is the memory address of the objects.

It's really the same issues as when you have to deal with equality in Java. See this Artima blog post about writing equals in Java (and Scala) written by Bill Venners, Martin Odersky, and Lex Spoon.