Skip to content

Inconsistent equality between boxes of doubles #329

@densh

Description

@densh

While developing Scala Native I've run into curious special case of Scala's equality on the JVM:

  val pzero = +0.0
  val nzero = -0.0
  println(pzero != nzero)
  val b1pzero: java.lang.Double = pzero
  val b1nzero: java.lang.Double = nzero
  println(b1pzero != b1nzero)
  val b2pzero: Any = pzero
  val b2nzero: Any = nzero
  println(b2pzero != b2nzero)

2.12.1's repl prints:

  false
  true
  false

And not:

  false
  false 
  false

@sjrd suspects that:

The reason is an "optimization" which, as your example shows, is a bug. It's there: https://github.com/scala/scala/blob/13f7b2a975ee77520535598fd192376b4d4b235e/src/compiler/scala/tools/nsc/backend/jvm/BCodeBodyBuilder.scala#L1266-L1275
The comment says that if both the lhs and rhs of == (or !=) are final subclasses of Number, then it uses their equals() method (as opposed to BoxesRunTime.equals). The comment argues that their equals() method will do just fine, but as your example demonstrates, this is not true for Doubles and Floats.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions