I have a case class which has 2 parameters of type Long
and String
. I was assuming that auto generated equals()
method would work as desired (meaning it really checks that the (Long, String)
pair is the same), but apparently it doesn't always do that. It seems like Scala generates equals method in which it checks equality of each member with ==
operator. Is this correct?
Asked
Active
Viewed 307 times
0
-
1Could you give an example of the unexpected observed behavior and tell which behavior you expected instead? – Didier Dupont Mar 20 '15 at 21:28
-
Seems like that behavior is not because of equals(). In case you're interested, I'm using apache Spark and there is a method called reduceByKey. This key in my case is a case class, and it produced some repeated values. That's why I was thinking that maybe equals doesn't work as I expected, but seems like there is some other issue. – llaki Mar 20 '15 at 21:40
-
Thanks for clarifying. Evidence of a problem with just a Long and a String parameter would have been a bit alarming :-) – Didier Dupont Mar 20 '15 at 21:46
1 Answers
3
In Scala, equals
and ==
are basically the same thing, except ==
handles null
, as explained here, or in the docs:
The expression
x == that
is equivalent toif (x eq null) that eq null else x.equals(that)
.
It is recommended to generally use ==
. Reference equality is checked using eq
(rare).
For case classes, equals
is automatically implemented (and therefore so is ==
which routes to equals
):
case class Foo(a: Long, b: String)
val foo1 = Foo(1L, "")
val foo2 = Foo(1L, "")
val foo3 = Foo(2L, "")
foo1 == foo2 //true
foo1.equals(foo2) //true
foo1 == foo3 //false
foo1.equals(foo3) //false
From the docs:
For every case class the Scala compiler generates an
equals
method which implements structural equality and atoString
method.