Search code examples
scalaequalitycase-classcompanion-object

What are the differences between "object equality" created by the factory method of the companion object and case class?


When comparing object equality through instances created by the factory method of the companion object, it will be false.

class Companion(s: String)
object Companion {
    def apply(s: String): Companion = {
        new Companion(s)
    }
}
val c1 = Companion("foo")
val c2 = Companion("foo")
println(c1 == c2) // false

But why will it be true when the same situation created by the case class?

case class Case(s: String)
val c1 = Case("foo")
val c2 = Case("foo")
println(c1 == c2) // true

What are the differences between those two?


Solution

  • Factory methods aren't relevant. Both in your first case, and for case classes they just call the constructor and so the code can be simplified to

    new Companion("foo") == new Companion("foo")
    

    and

    new Case("foo") == new Case("foo")
    

    Because Companion doesn't override equals (or inherit from a class/trait overriding equals), you get Object's definition which is reference equality and false for any two different instances.

    Case overrides equals because it's a case class, and the implementation simply compares s values.