Difficulty of compareTo on floats/doubles

John Rose john.r.rose at oracle.com
Thu Jul 31 20:56:51 UTC 2014

On Jul 31, 2014, at 12:43 PM, Alex M <timeroot.alex at gmail.com> wrote:

> strange problems

The essential point here is discussed in passing (see "simple relationals") in the value type prospectus.

Yes, there are a lot of these strange problems that arise from forcing both primitives and objects under one type bound.

More generally, the semantic oddities of "==" for float, double, and references make it very tricky indeed to apply "==" (and other operators, notably "+") to extremely polymorphic variables bounded by "any".

Although it may not be practical in the end, my personal preference would be to deprecate or disallow operators on polymorphic variables, and express everything with method invocation.

Method invocation on a non-reference value can be uniformly and simply defined by delegation to a boxed version of the value. If we define new box types (not impossible though difficult) we can take extra care to have the ad hoc polymorphism be as consistent as possible across the expanded range of types.  We provide for such consistency already in the documentation of interfaces like Comparable and (as Joe explained) methods like Double.compareTo.

Pre-existing boxes are probably not adequate to this.  Null references may also require a "boxing" rule of some sort.

See also the "vcmp" instruction in the value types prospectus.  For value types we think we can make a compatible story of how to cope with "==" and ".equals":  "==" is bitwise and ".equals" is a method call (possibly boxed, but the user cannot observe whether that happens).

Bottom lines:  Consistent ad hoc polymorphism is hard, especially when unifying legacy types.  And see "vcmp" for bitwise semantics and extend it if necessary to primitives.  But try hard to do most things in terms of methods, which is more flexible and explicit.

— John

More information about the valhalla-dev mailing list