Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a zero value of a generic Number subclass

Tags:

java

generics

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?

like image 775
Bennett McElwee Avatar asked Aug 23 '10 02:08

Bennett McElwee


1 Answers

Is it possible to do this at all?
Not really. For one thing, when value is null, how would method know which Number implementation to return?

like image 77
Nikita Rybak Avatar answered Oct 12 '22 15:10

Nikita Rybak