Domanda

I have a question concerning Scala case classes. I have a case class that is a composition of other types as below:

case class MyCaseClass(typeA: TypeA, typeB: TypeB) {
 override def equals(obj: scala.Any): Boolean = super.equals(obj) // generated by intelliJ
}

Both my TypeA and TypeB are normal Scala classes and what I want is that, two instances of MyCaseClass is equal only if all the properties of typeA and typeB are equal. I could of course do this check in the equals method directly in my case class like below:

case class MyCaseClass(typeA: TypeA, typeB: TypeB) {
....
  def equals(obj: Any): Boolean = obj match {
    case myCase: MyCaseClass => myCase.typeA.equals(myCase.typeB)
    case _ => false
  }
}

With respect to the example snippet above, I have the following questions:

  1. If my TypeA is a case class and my TypeB is a normal Scala class, would this means that I have to implement equals method just in TypeB where in my TypeA being a case class would get the equals method by default and I do not have to provide one?

  2. My MyCaseClass would be used in such a way that I have a sequence of MyCaseClass and a primitive value (Double or Integer) as a tuple Seq(MyCaseClass, Double). Now if I do a groupBy operation on MyCaseClass from the Sequence, will they be groupedBy based on the equals method?

È stato utile?

Soluzione

You're inheriting nothing, so the super.equals you're getting, possibly that of Product2 (assuming it has a meaningful one of its own) or scala.ScalaObject, is probably not what you want.

But the real question is why are you altering the semantics of the compiler-supplied equals?

Lastly, if there's any doubt in your mind (as evidenced by asking a question on Stack Overflow) when it comes to writing your own equals, it behooves you to read chapter 28, "Equality," of Programming in Scala. Hint: Writing truly correct equals is not trivial. That chapter is 26 pages long! (Note: I have only the 1st ed. at hand.)

Frankly, as infrequently as I need to write my own equals, I end up consulting that chapter every time I do.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top