On Sat, Apr 30, 2016 at 12:26 AM, guilhermebla...@gmail.com < guilhermebla...@gmail.com> wrote:
> Wrong. This is documented here > https://docs.oracle.com/javase/tutorial/java/generics/upperBounded.html > and specifically states: > > To write the method that works on lists of Number and the subtypes of >> Number, such as Integer, Double, and Float, you would specify List<? >> extends Number>. The term List<Number> is more restrictive than List<? >> extends Number> because the former matches a list of type Number only, >> whereas the latter matches a list of type Number or any of its >> subclasses. > > > I think that documentation confirms what I wrote, but I guess it depends how you read it. In any case here is the corresponding Java code, with the output from javac for the lines that produce errors. You can test it yourself. package com.testvariance; import java.util.LinkedList; import java.util.List; class C { } class A extends C { } class B extends A { } public class Main { public static void main(String[] args) { // You can add subtypes of A to List<A> in Java List<A> la = new LinkedList<A>(); la.add(new B()); // So if B extends A, List<B> is compatible with List<? extends A> List<? extends A> lb = new LinkedList<B>(); // when reading items you can assume they will be compatible with A (since B extends A) A a1 = lb.get(0); // but you can't add an A (because it's actually a list of Bs) lb.add(new A()); // Error:(25, 14) java: no suitable method found for add(com.testvariance.A) // So if A extends C, List<C> is compatible with List<? super A> List<? super A> lc = new LinkedList<C>(); // and you can add an A (because A is compatible with C) lc.add(new A()); // but when reading items you can't assume they're going to be As (because it's actually a list of Cs) A a2 = lc.get(0); // Error:(33, 28) java: incompatible types: capture#2 of ? super com.testvariance.A cannot be converted to com.testvariance.A } } > > Rasmus is purely following already defined PHP covariance definition that > currently exists for type hinting into generic types. > Wait, where does PHP already define covariance? The only type of generic I've ever seen in PHP is Foo[] generic array types in PhpDoc (which of course would be covariant because arrays are pass-by-value, unlike objects). AFAIK type hinting is presently restricted to plain classes/interfaces/scalars/array/callable, no generics at all. Java differs from that and accept covariance for type definitions, but > restricts for generic types. > > -- > Guilherme Blanco > Lead Architect at E-Block >