3 ms·
> In a language like Java, I could write this function to accept any type for which the + operator is valid, and it would still be type safe at compile time. I
by mseepgood 8y ago
> In a language like Java, I could write this function to accept any type for which the + operator is valid, and it would still be type safe at compile time. I would not need to assert the types like I did above.
Really? No. Not in Java.
static <T extends Number> void someAdditionFunction(T arg1, T arg2) {
System.out.println("Sum:", arg1 + arg2);
}
"error: bad operand types for binary operator '+'"
- erik_seaberg 8y agoYeah, it works with methods, but unfortunately arg1 + arg2 isn't implemented by calling a method on Number.
- dtech 8y agoThat's because + is a java built-in unavailable to normal types. Usually something like an add method is used instead. It does not detract from the underlying point.