2 ms·
No. Mutation essentially breaks subtyping. The infamous ArrayStoreException in Java is the story of how references (which should be invariant) are treated as co
by kccqzy 9y ago
No. Mutation essentially breaks subtyping. The infamous ArrayStoreException in Java is the story of how references (which should be invariant) are treated as covariant and therefore causes runtime exceptions.
- fnl 9y agoWhich is only because Java doesn't understand contravariance. In Scala, that problem no longer exists.
- kccqzy 9y agoNo. When references or arrays of references are treated as contravariant, you would have the opposite problem of ArrayReadException. You can now store things into arrays safely but you can no longer extract things from arrays safely.
- fnl 9y agoConsumers are contravariant in Scala, but producers are covariant. EDIT: Good reference: https://www.atlassian.com/blog/software-teams/covariance-and-contravariance-in-scala https://www.atlassian.com/blog/software-teams/covariance-and...
- KMag 9y agoIf your array type (the only reified generic type in Java) is going to be parameterized by a single type, then you're right that it needs to be invariant. One alternative would be to keep track of two types for an array: the most general type that can be stored into it and the most general type that might come back out of it. Any type cast that makes the types storable more strict or the type expected coming out less strict should be allowed. If you throw in a bottom type in your type system, then you get immutable arrays for free. Of course, such a type system would probably cause a revolt among the majority of Java programmers for being too complex.