English 中文(简体)
Scala semantics of equals/hashCode for case classes with traits
原标题:

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.

最佳回答

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)
问题回答

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.





相关问题
Inconsistency on equals() applied to Vector

Vector <Double> x = new Vector<Double>(); Vector <Integer> y = new Vector <Integer>(); System.out.print(x.equals(y)); This prints: true Why? Isn t equals() -by default- ...

Best way to write an or is equal statement

Hello $mostamazingforumforfastanswersever. I have a quick silly question; what is the best way to write this : if ($curpageurl == "www.mysite.com/this" || "www.mysite.com/this/") { echo this is ...

Why say x = x in Python?

In this file, in the function cross_from_below(x, threshold), there is a line that says threshold = threshold. What s the point of this line? Does this do something differently than if this command ...

Java: .equals() failing for sets (JGraphT)

I can t figure out what s going wrong here. This test fails: @Test public void testSimpleCase() { assertTrue(JGraphtUtilities.graphEquality(ChooseRootTest.generateSimpleCaseGraph(), ...

C# - How to override GetHashCode with Lists in object

I am trying to create a "KeySet" to modify UIElement behaviour. The idea is to create a special function if, eg. the user clicks on an element while holding a. Or ctrl+a. My approach so far, first ...

热门标签