Search code examples
scalascalatestassertioncase-class

Assertion for overloaded equality operator fails for triple-equals but passes for double-equals


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?


Solution

  • You spelled it wrong. ;)

    It should be:

    override def equals(x: Any): Boolean