Create a zero value of a generic Number subclass

Viewed 5333

How can I generically create a zero of an arbitrary numeric type?

Here's a toy example: a function that converts a null number into zero.

static <T extends Number> T zeroIfNull(T value) {
    return value == null ? 0 : value;
}

This doesn't compile because the literal zero is of type int, and I need to convert that to type T.

Is it possible to do this at all?

8 Answers

This method requires a typeclass so you either need a T object instance to get it from, or the typeclass directly.

T castedValue = NumberCast.cast((Class<T>)someTObject.getClass(), 0d);

public class NumberCast
{
    public static <T extends Number> T cast(Class<T> typeClass, double value)
    {
        if (typeClass == Double.class)
            return typeClass.cast(value);
        else if (typeClass == Float.class)
            return typeClass.cast((float)value);
        else if (typeClass == Integer.class)
            return typeClass.cast((int)Math.round(value));
        else if (typeClass == Short.class)
            return typeClass.cast((short)Math.round(value));
        else if (typeClass == Long.class)
            return typeClass.cast(Math.round(value));

        return null;
    }
}

You can use method overloading to achieve this:

public static Double getValue(Double value) {
  return value != null ? value : 0;
}

public static Long getValue(Long value) {
  return value != null ? value : 0;
}

public static Integer getValue(Integer value) {
  return value != null ? value : 0;
}
Related