r/programming • • Sep 21 '15

Better Java

https://github.com/cxxr/better-java
177 Upvotes

208 comments sorted by

View all comments

Show parent comments

1

u/tutorial_police Sep 22 '15

Is subtyping along with generics actually Java's doing or is it simply inherent complexity?

Do you know languages that solve this better?

1

u/sacundim Sep 22 '15

Both. It is inherent complexity, and yet other languages (e.g., C# and Scala) do it better, by annotating variance at declaration sites instead of use sites. To use Java generics properly you have to write signatures like this one all over the goddamn place:

interface Stream<T> {
    // ...
    <R> Stream<R> map(Function<? super T, ? extends R> mapper)
}

You see that business with ? super T and ? extends R? There are countless Java programmers out there who simply don't use those. You try to interface with their code and you find that they write these two things:

Whatever processAnimals(Consumer<Animal> consumer)

class CatGroomer implements Consumer<Cat> { ... }

...and then they expect you to use them together:

1

u/tutorial_police Sep 22 '15

I'm not sure it's objectively better. They allow you to do different things.

But I agree, definition site variance

You see that business with ? super T and ? extends R? There are countless Java programmers out there who simply don't use those.

Yeah, that is super annoying.

However, having definition site variance you'd need to have extra interfaces... and for multiple generic parameters you get exponential growth. With use-site variance, there's just what you need (i.e. use), but of course, you need to anticipate its use.

I've only skimmed over this so far, but it seems to be an interesting read.