Search code examples
scalaequalshashcodebigdecimal

Does Scala's BigDecimal violate the equals/hashCode contract?


As the Ordered trait demands, the equals method on Scala's BigDecimal class is consistent with the ordering. However, the hashcode is simply taken from the wrapped java.math.BigDecimal and is therefore inconsistent with equals.

object DecTest {
  def main(args: Array[String]) {
    val d1 = BigDecimal("2")
    val d2 = BigDecimal("2.00")
    println(d1 == d2) //prints true
    println(d1.hashCode == d2.hashCode) //prints false
  }
}

I can't find any reference to this being a known issue. Am I missing something?


Solution

  • The people over on the Scala User mailing list seem to agree that this is a bug. I guess it's not been picked up until now because no-one has ever used a BigDecimal as a key in a hash structure. It's been filed as bug #2304