3 ms·
What? No. T is a subtype of T?, so I don't get where you are going. If a generic function f accepts a covariant Dog and Animal is a supertype of Animal you can
by dtech 8y ago
What? No. T is a subtype of T?, so I don't get where you are going.
If a generic function f accepts a covariant Dog and Animal is a supertype of Animal you cannot call f with Animal because it requires a Dog. if f accepts a covariant Animal you can call it with a Dog because Dog is a subtype of Animal.
Now replace Dog with T and Animal with T? and you can see it is perfectly fine.
- lmm 8y agoWe're talking about generics. <T> and the like. I can have a Map<String, Dog>, I can have a Map<String, Animal>, and these are different things but they both work fine because both Dog and Animal are first-class types. Can I have a Map<String, Dog?> ? If no, then Dog? isn't a first-class type. If yes, we have all sorts of nasty surprises, because code written in terms of Map<String, T> will assume that if map.get(someKey) is null then that means someKey isn't in the map, and this code will work fine until someone uses a ? type for T and then break horribly.
- dtech 8y ago> Can I have a Map<String, Dog?> yes > because code written in terms of Map<String, T> will assume that if map.get(someKey) is null that means someKey isn't in the map And it can safely assume that. Map<String, T?> isn't a subtype of Map<String, T>, so passing Map<String, T?> to a place requiring Map<String, T> will not compile. T is a subtype of T?, not the other way around. Map is defined as Map<K, out V>, meaning V is covariant. So you can pass a Map<String, Dog> where a Map<String, Dog?> is required, but not a Map<String, Dog?> where a Map<String, Dog> is required.