Numeric

Brian Goetz brian.goetz at oracle.com
Fri Sep 14 14:10:10 PDT 2012


> Long-term, we need primitive specialization of generics.  But shorter
> term, there's an intermediate solution that reduces both boxing and
> combinatorial explosions of special forms. The tradeoff is to accept
> some virtualness, plus a bit of tedium on the part of components
> implementing it:
>
> /**
>   * Interface defining access methods for classes that provide numeric
>   * results. A {@code Numeric} is not itself an instance of {@link
>   * java.lang.Number}, but provides numeric methods to access its
>   * primary result or property; normally via the method corresponding
>   * to the listed {@code PreferredType} parameter. However, any
>   * implementation of this interface must define the non-preferred
>   * methods as well (typically by casting the results of the
>   * preferred form).
>   */
> public interface Numeric<PreferredType extends Number> {
>      long getLong();
>      int getInt();
>      short getShort();
>      byte getByte();
>      double getDouble();
>      float getFloat();
> }

These guys also need companion classes that are mutable, so that 
reductions can have O(1) boxing costs instead of O(n).

class IntMutableNumeric implements Numeric<Integer> {
     private int value;

     public setInt(int value) { this.value = value; }

     // obvious getter implementations
}

This would be really useful in the groupBy+reduce case:

Map<Name, Numeric<Integer>> highScoresByName =
     scores.foldBy(s -> s.getName(),
                   () -> new IntMutableNumeric(),
                   (bx, s) -> bx.setValue(Math.max(bx.getValue, s)));

The knowledge that the values are mutable does not escape from the 
initializing computation.



More information about the lambda-libs-spec-experts mailing list