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?
A class can extend another class, whereas a case class can not extend another case class (because it would not be possible to correctly implement their equality).
What is Scala Case Class? A Scala Case Class is like a regular class, except it is good for modeling immutable data. It also serves useful in pattern matching, such a class has a default apply() method which handles object construction. A scala case class also has all vals, which means they are immutable.
A case class can take arguments, so each instance of that case class can be different based on the values of it's arguments. A case object on the other hand does not take args in the constructor, so there can only be one instance of it (a singleton, like a regular scala object is).
While all of these features are great benefits to functional programming, as they write in the book, Programming in Scala (Odersky, Spoon, and Venners), “the biggest advantage of case classes is that they support pattern matching.” Pattern matching is a major feature of FP languages, and Scala's case classes provide a ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With