Writing a hashCode method for a class in Scala 3

33 views Asked by At

I am working through Scala for the Impatient (3rd) Edition by Horstmann. I'm scratching my head over this assignment.

Write a class Circle with a center and a radius. Add equals and hashCode methods. Activate multiversal equality.

I'm not sure how to implement the hashCode method. This is what I came up with.

package circle:
    import scala.language.strictEquality

    class Circle(val radius: Double, val x: Double, val y: Double):
        def centerPoint = (x, y)
        final override def equals(other: Any) =
            other match
                case a: Circle => radius == a.radius && centerPoint == a.centerPoint
        override def hashCode(): Int = radius.hashCode() + x.hashCode() + y.hashCode()

I'm pretty sure that's wrong though.

  val circle1 = Circle(2.0, 0, 0)
  print(s"Circle center: ${circle1.centerPoint}\n")
  print(s"Circle radius is: ${circle1.radius}\n")
  print(s"circle1 hashCode: ${circle1.hashCode()}\n")
  val circle2 = Circle(2.0, 0, 0)
  print(s"Is circle1 equal to circle2? ${circle1 == circle2}\n")
  print(s"circle2 hashCode: ${circle2.hashCode()}\n")

Yields

Circle center: (0.0,0.0)
Circle radius is: 2.0
circle1 hashCode: 1073741824
Is circle1 equal to circle2? true
circle2 hashCode: 1073741824

If memory serves, hashes are supposed to be unique, so I'm pretty sure I'm doing something wrong. Should I be using hashCode? I have noticed in several posts that users are using ##, which is supposed to be memory safe.

0

There are 0 answers