I've got a little but annoying problem with use of Generics in a Function.
The Function has to convert into a Double any value that could be BigDecimal or BigInteger. That's why I designed it with a <T> type for incoming argument.
The problem is that when I'm using it, I have to cast the given argument with <T>...
Here is the code of the Function:
private Function<T, Double> bigToDouble = value -> {
BigDecimal bigDec = null;
if (value instanceof BigInteger) {
BigInteger bigInt = (BigInteger) value;
bigDec = new BigDecimal(bigInt);
}
if (value instanceof BigDecimal) {
bigDec = (BigDecimal) value;
}
return NumberUtils.toDouble(bigDec, NumberUtils.DOUBLE_ZERO);
};
When I test it, I've got an error if I do not cast the given argument with <T> :
BigDecimal bigDec = new BigDecimal("2.5");
BigInteger bigInt = new BigInteger("150000");
System.out.println("FUNCTION TEST = " + bigToDouble.apply((T) bigInt));
System.out.println("FUNCTION TEST = " + bigToDouble.apply((T) bigDec));
What I expect is to call it this way, simply:
bigToDouble.apply(bigInt)
How should I design it to avoid such behaviour?
NumberUtils.toDouble(bigDec, NumberUtils.DOUBLE_ZERO)do? How is it different from, say,bigDec.doubleValue()? Why don't you usedoubleValue()directly in the first place?<T extends Number, Double>?Function, not a method. A field can't have a generic parameter likeT.Thas to be declared somewhere).NumberUtils.toDouble(bigDec, NumberUtils.DOUBLE_ZERO)(if that's really necessary). That would make it easier to use - just not as a function. Btw, what exactly are you trying to do in the end? How do you intend on using that function? I have a feeling that we're looking at a xy-problem here.