3 ms·
It is both. Passing collections of subtypes where a read-only collection of supertypes is expected by the receiving code is fine, because the receiving code ca
by int_19h 10y ago
It is both.
Passing collections of subtypes where a read-only collection of supertypes is expected by the receiving code is fine, because the receiving code can't do anything that would break type safety.
But Java decided to only have a single array type, as a matter of expediency. But they also wanted covariance, because, as you point out, sometimes it's just convenient - more expediency. And so the trade-off was to enforce safety at runtime.
It's still a defect in a sense that the design itself could be made sound, if there were a read-only array reference type in Java.
- marvy 10y agoRead-only is too strict. Can't reverse the array, or sort it.
- int_19h 10y agoSure you can - you just need to copy it. And I didn't mean to imply that array references should always be read-only. What I meant is that there should be a way to say "the referenced array cannot be mutated through this reference", like const* in C. 90% of the time, when you pass or return arrays, this is exactly what you want.