Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is it possible to ignore a field of a case class in the equals/haschode method of the case class?

My use case is that I have a field that is essentially metadata for rest of the data in the class.

question from:https://stackoverflow.com/questions/10373715/scala-ignore-case-class-field-for-equals-hascode

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
283 views
Welcome To Ask or Share your Answers For Others

1 Answer

Only parameters in the first parameter section are considered for equality and hashing.

scala> case class Foo(a: Int)(b: Int)
defined class Foo

scala> Foo(0)(0) == Foo(0)(1)
res0: Boolean = true

scala> Seq(0, 1).map(Foo(0)(_).hashCode)
res1: Seq[Int] = List(-1669410282, -1669410282)

UPDATE

To expose b as a field:

scala> case class Foo(a: Int)(val b: Int)
defined class Foo

scala> Foo(0)(1).b
res3: Int = 1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...