Settings

Theme

Why isn't mutable a subtype of immutable, or vice versa?

crumbles.blog

11 points by ibobev · 9 comments

Reader

4 threads
raincole

In other words, immutable != read only.

In C# ReadOnlyCollection<T> and ImmutableArray<T> are two completely different things for this exact reason.

comrade1234

Isn't NSMutableArray a subclass of NSArray in a few languages?

  • bartvk

    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).

  • catoc

    Yes, that’s ObjC, any NSMutableArray is an NSArray (and an NSObject) - classes passed by reference.

    Swift is completely different. Standard arrays are structures, always mutable - value types passed by value

zkmon

The fact that it requires so much explanation, indicates the level of degradation in the reasoning ability of the audience. A value of a subtype shall deliver all of the expectations of its super type, because it is wearing both the hats of super type and sub type.

gus_massa

Yep, I wondered that for a few optimizations in Racket. It's harder than it looks, probably something about covariant or contravariant types, I gave up.

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection