Comment by bartvk

3 hours ago

Good one, yes. It was like that in Objective-C, and in the early versions of Swift. I know you know this, but it's useful to summarize for myself:

Basically inheritance is the wrong tool for this kind of stuff. NSMutableArray inherits from NSArray, so it can be passed to anywhere NSArray is expected (upcasting).

So you design your classes and expect them to be immutable, but you can't use NSArray anywhere. Because otherwise, it'll be mutable after all. You can do a runtime check as a workaround.

(I truly believe OOP should only be taught in computer science as a relic).

You just misinterpreted what NSArray is. It’s not an immutable type, it’s a read-only type. As others already mentioned that’s different things. If you have a read-only variable and exclusive access to it, then you can rely on immutability as well. This is what Rust has, for example. Many languages use this definition as well as it’s much more useful than having some sort of pure immutable type guarantee (which some languages do have with const). Another language that uses this is Kotlin: List is a read-only type. MutableList is a subtype of List. You can get a “const” List by only keeping a reference to the value via a List binding. This can be worked around via casting and reflection, but even in Haskell you can do unsafe things that mutate a immutable value, so I don’t think that undermines the idea.