0

I overloaded a case class's equality operator:

case class Polygon(points: Seq[(Double, Double)]) extends Shape {
  def ==(that: Polygon): Boolean = { ... }
}

My unit tests pass when using double-equals in assertions:

import org.scalatest.FunSpec

class ShapeSpec extends FunSpec {
  describe("Polygon") {
    it("is equal to all its rotations") {
      val p = Polygon(Seq( ... ))
      for { i ← 0 until p.points.size } {
        val q = Polygon(p.points.drop(i) ++ p.points.take(i))
        assert(p == q)
      }
    }
  }
}

But when using === instead of ==, the same tests fail:

[info] Polygon
[info] - is equal to all its rotations *** FAILED ***
[info]   Polygon(List((-1.0,-1.0), (4.0,-1.0), (4.0,2.0), (1.0,2.0),
         (1.0,1.0), (-1.0,1.0))) did not equal PolygonM(List((4.0,-1.0),
         (4.0,2.0), (1.0,2.0), (1.0,1.0), (-1.0,1.0), (-1.0,-1.0)))
         (ShapeSpec.scala:28)

Why does this happen?

Roberto Bonvallet
  • 31,943
  • 5
  • 40
  • 57
  • 1
    because `===` uses [`equals()`](http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html) method automatically generated for your case class – dk14 Apr 09 '15 at 20:15
  • see http://stackoverflow.com/questions/7681183/how-can-i-define-a-custom-equality-operation-that-will-be-used-by-immutable-set – dk14 Apr 09 '15 at 20:19

1 Answers1

3

You spelled it wrong. ;)

It should be:

override def equals(x: Any): Boolean
Alex Cruise
  • 7,939
  • 1
  • 27
  • 40
  • Thanks! For reference, I found [this article](http://www.artima.com/pins1ed/object-equality.html) which explicitly states that the way I was doing it is “an utterly wrong definition of equals.” – Roberto Bonvallet Apr 09 '15 at 20:39