How to handle numbers in a generic fashion?

generics, java

Solution

The fundamental problem is with the Java type system which is very primitive.

Since there is no notion of a sealed set of types in Java (nor is it possible for Java to infer the types like Haskell does) there is no way to make make a general Number + Number -> Number without trickery.

For primitives (and those objects like Integer which can be automagically mapped to them) types promotion and the + operation is part of the language. (And this is actual part of the problem: what should Number a + Number b return where a and b are of different types?)

If you really want this behavior you'll have to find (or create) your own custom class that either uses reflection or a series (of checks and) casts and such. Even if you use generics (remember that generics are type-erased) casting will need to be done.

I imagine these problems are part of the reason why Number is as bland as it is.

Problem

My question is eerily similar to "Writing a generic class to handle built-in types" including being inspired by the fact of working on a class to handle operations on matrices. Although that question was asked using C# and pointed to an article on Generic Operators. I don't get it. Java Number does not have an add method so you can have a method like: ``` public Number myAdd(Number a, Number b){ return a.add(b); } ``` So how do you handle a case where you want to be able to handle multiple types of Numbers in Java?

Original source