I think in Java, you would need to do a type-class approach. interface Numeric { T zero(); T add(T a, T b); } static T sum(Numeric n, T[] v) { T summer = n.zero(); for (int k = 0; k
Honestly I have no idea what's going on with this code. Where is `zero()` defined? Why does a `Numeric` have a function to `add` two numbers? Shouldn't you add a single number to a numeric? What is the relationship between ` ` and `Numeric `? I thought `T` was a `Numeric`? Edit: Upon closer inspection, I kind of get what's going on. But it's really cryptic for something that should be simple to express.
There are probably other reasons to do this that I'm forgetting, but off the top of my head,
1. You can implement `Numeric` or `Comparator` for types `T` that come from a library that you can't change (so can't make T implement an interface that the library author didn't implement), or where you don't want to introduce a dependency (you could have a type class `JsonDecoder[T]` that comes from a library, and you don't want the library with your T to introduce a dependency on the json library).
2. You can have more than 1 implementation for a given T. For JSON decoders/validators, you might provide a decoder which bails out on the first error, or one which tries to continue reading fields so it can return all errors (field X was a string, expected number. Field Y was expected to be >= 1024, etc.). For comparators, you might have a `.reversed` function to easily make a comparator that sorts in reverse order. etc.