4 ms·
The mutability is a red herring here. It depends on what methods your object has and where the generic type resides within the signature. It just so happens tha
by PhilipRoman 2y ago
The mutability is a red herring here. It depends on what methods your object has and where the generic type resides within the signature. It just so happens that an immutable array has only one relevant "method":
get :: Int -> T
Here, T is on the right/return side, therefore an immutable array type would be covariant. But a mutable array also has a
set :: Int, T -> void
which has T on the left/parameter side and therefore requires contravariance (and you cannot have both, therefore you get invariance).
But the issue is not with mutability, since you could just as well have something like
setImmutable :: Int, T -> Array(T)
and you still wouldn't be able to make Array(T) covariant.
And for the record, it is only raw arrays in Java that have this issue, generic types like List<T> are invariant (of course you can explicitly ask for a List<? super T> if you want to only call "setter" type methods on it, or List<? extends T> for getters, aka methods where T appears only on return side).
- nlitened 2y agoThis setImmutable would return a new instance of Array<Animal> which would not be Array<Cat> like the original, and would contain any mix of cats and dogs. So immutability resolves the covariance problem, I think?
- dwattttt 2y agoI've never quite understood enough about types to know why, but: it's more like the difference between read-only and write-only. One of the variances is safe if you only read, and one is safe if you only write.
- deleted 2y ago[deleted]
- PhilipRoman 2y agoMy main point was that mutability and covariance are two orthogonal concepts that just happen to overlap here due to function signature shape. But it seems that you are right, I cannot think of any expression that would type-check with Array<Animal> but not with Array<Cat>. ChatGPT was very unhelpful in trying to produce a counterexample, since it probably trained on too many entry level stackoverflow posts about this issue.