Why isn't mutable a subtype of immutable, or vice versa?
This article explores the theoretical reasons why mutable and immutable data structures cannot be treated as subtypes of one another in programming languages. It explains that the Liskov substitution principle prevents such subtyping to maintain type safety and prevent runtime errors.
Why it matters
Understanding these type theory constraints is essential for software engineers designing robust, bug-free APIs and language features.
I remember the moment when I learned about immutability. It changed everything.
Periodically, in various programming language forums, the discussion comes up of why a certain language doesn’t provide the immutable and mutable variants of some data structure as subtypes or supertypes of one another. Now, it’s not impossible to do this, but it’s actually not formally correct to do so, and by doing so you’ll lose at least some of the type checking guarantees your language can usually make for you.
To understand why this doesn’t work, you have to remember the definition of a subtype. Namely, Liskov’s subsitution principle : a type S is a subtype of T if a value of type S can be used in every context where a value of type T is expected.
Get smarter about the news
Sign up free for a feed built around what you actually care about, Dive Deeper research on any story, and the full text of every article.
Create free accountAlready have an account? Sign in