Reputation: 33
I am a newcomer to Scala. In 2.7.7, the following code
abstract class C
case class CC() extends C
trait T
val c1 = CC()
val c2 = new CC() with T
println(c1.hashCode == c2.hashCode,c1 equals c2)
prints
(false,true)
whereas I would have expected
(false,false)
What am I missing? Thanks in advance.
Upvotes: 3
Views: 1653
Reputation: 4580
Case class equality (particularly in Scala 2.8) equality and hash codes are based upon tuple and/or product equality, and do not currently take the class into account. There was a recent discussion on this matter on the scala-debate mailing list here: http://old.nabble.com/Possible-Collision-Issue-with-Product.hashCode-td27026790.html
For what it's worth, here's what it currently looks like in 2.8:
Welcome to Scala version 2.8.0.Beta1-RC6 (Java HotSpot(TM) Client VM, Java 1.6.0_16).
Type in expressions to have them evaluated.
Type :help for more information.
scala> abstract class C
defined class C
scala> case class CC() extends C
defined class CC
scala> trait T
defined trait T
scala> val c1 = CC()
c1: CC = CC()
scala> val c2 = new CC() with T
c2: CC with T = CC()
scala> println(c1.hashCode == c2.hashCode,c1 equals c2)
(true,true)
Upvotes: 8
Reputation: 6715
This behaviour is expected for equals since the Scala compiler overrides the equals method for case classes.
I am however unsure why the hashCode is different in Scala 2.7.7. Your example results in (true, true) using Scala 2.8.
Upvotes: 2