Hacker News new | ask | show | jobs
by ootachi 5192 days ago
I have a feeling you're going to get a bunch of type theorists instead of programmers who get things done if you ask about Java's syntax for use-site contravariance.
2 comments

Not true. You'll get, for instance, people who read Effective Java [1], by Joshua Bloch (who is, IMHO, THE man when it comes to java), and remembered the PECS mnemonics. PECS stands for producer-extends, consumer-super.

So, to cite the textbook example, say you are implementing a Stack<E>. It will probably have the methods:

  public void push(E element);
  public E pop();
and, for convenience:

  public void pushAll(Iterable<? extends E> elements);
  public void popAll(Collection<? super E> destination);
The pushAll has "? extends" because the elements Iterable will "produce" elements for the stack. The popAll has super because the destination Collection will "consume" elements from the stack. It is not that hard, is it? Let's note that guard-of-terra is talking about proficiency, not mere familiarity. I believe reading "Effective Java" is a nice way to get closer to the proficient level.

Let it be noted that this whole mess exists because generics in Java were implemented with type erasure so their introduction wouldn't break legacy code. I personally think this was a bad idea, but it does show that when a language is evolving, there are a bunch of constraints the designers must be aware of.

[1] http://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp...

This doesn't seem to have anything to do with type erasure, does it? It's needed for type-safe generics. Even without type erasure, you still need type safety. If your generics are always covariant (like Dart's are), you break type safety.

I think the mistake the Java designers made here was going with use-site variance instead of definition-site variance.

Yes, you're right. We're talking about variance when it comes to the "? extends, ? super" situation, not erasure. And you're also right the things would be better with definition-site variance.

On the other hand, sometimes I think an unsound type system with List<String> being a subtype of List<Object> would be better than what we have today, for pragmatic reasons. Of course, I think this makes me a non-type-theorist, as what I'm saying is considered heresy in some circles [1].

[1] http://lambda-the-ultimate.org/node/4377 (search for unsound).

But than you can never get anything from List<String>! Because you never know what type are you getting!

On the other hand, if your structure is immutable it would probably work.

"? extends" is a cool question because even if you know nothing theoretical about generics, you can figure it out with a few hints because it does have an actual underlying reason. Or you can't - even with massive hinting some people are just afraid to guess and reason. So it's a nice test.