4 ms·
This is incorrect. The type system of both languages makes sure that T does not include null, so the case where you "accidentally" handle the null of T is impos
by dtech 8y ago
This is incorrect. The type system of both languages makes sure that T does not include null, so the case where you "accidentally" handle the null of T is impossible.
More generally, with unions you always have this behavior but I've never seen this be a problem. If your function accepts T | U and you pass (T | U) | U it simplifies to T | U and in my experience the code that handles U is always the correct thing to do for U.
- lmm 8y ago> The type system of both languages makes sure that T does not include null, so the case where you "accidentally" handle the null of T is impossible. So does that mean you can't call generic methods with ? types? Because there's an excluded middle here: either something like String? is a first-class type, in which case you can invoke a <T> T ... method with T=String? and then any T?s inside that method have the potential to misbehave, or you can't, in which case String? becomes an awkward second-class type.
- dtech 8y agoWhat? 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.