Right, which is why List has to be invariant (the only variance supported
by Java).  Iterable<String> can safely be a Iterable<Object> logically but
not in Java, and Comparator<Object> can safely be a Comparator<String>
logically but not in Java.  We have wildcards that can help but they have
to be repeated everywhere to be useful and make compiler error messages
harder to read.  In the ##java IRC channel I generally advise people
struggling with generics to drop wildcards if they can.

The problem you pointed out is exactly the problem that Java arrays have,
except at least they throw an exception at runtime.

On Mon, Jul 30, 2012 at 4:20 PM, Fabrizio Giudici <
[email protected]> wrote:

> On Mon, 30 Jul 2012 21:07:05 +0200, Ricky Clarkson <
> [email protected]> wrote:
>
>  What hole do you see in Scala and C# if covariance and contravariance open
>> holes in type safety?  There may well be a problem I don't know of.
>>
>
> In Java if you have a List<String> and you can access it as a
> List<Object>, you can put any object inside it:
>
> List<String> ls = new ArrayList<String>();
> List<Object> lo = ls; // illegal in Java, suppose it is ok just for now
>
> lo.add(new Date());
> String s = ls.get(0); // ClassCastException at runtime.
>
>
> I don't know about C# and Scala: so somebody please tell me how the
> problem above is avoided.
>
>
>
> --
> Fabrizio Giudici - Java Architect, Project Manager
> Tidalwave s.a.s. - "We make Java work. Everywhere."
> [email protected]
> http://tidalwave.it - http://fabriziogiudici.it
>

-- 
You received this message because you are subscribed to the Google Groups "Java 
Posse" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/javaposse?hl=en.

Reply via email to