Conceptcore
Immutability
Also called immutable object, immutable value, read-only.
An immutable value cannot change after the program makes it. A program that needs a different value makes a fresh one, so every holder of the value sees the same state.
- Applies to
- core-languages
Idea
An object is immutable when its value cannot change after the program makes it. A program that needs a different value makes a fresh object. The Python glossary uses this definition: an immutable object has a fixed value, and a different value needs a fresh object.1 The opposite is a mutable object, such as a Python list, whose contents change in place.2
The difference matters when two parts of a program hold the same object. In this run, a function changes the list that the caller gave it. The caller's list changes too, because both names refer to one object.
This code runs but gives a wrong answer on purpose.
def add_tax(prices):
for i, price in enumerate(prices):
prices[i] = round(price * 1.2, 2)
return prices
base = [10.0, 20.0]
with_tax = add_tax(base)
print(base, with_tax)
[12.0, 24.0] [12.0, 24.0]
Without immutability, the usual guard is a defensive copy: the function or the caller copies the list before the change. With a tuple, the function cannot change its argument. It must return a fresh tuple, and the caller keeps the original.
def add_tax(prices):
return tuple(round(price * 1.2, 2) for price in prices)
base = (10.0, 20.0)
with_tax = add_tax(base)
print(base, with_tax)
(10.0, 20.0) (12.0, 24.0)
Immutability gives these properties:
- Sharing without copies. Two holders can share one immutable object, because neither of them can change it for the other. The Java
Stringclass says that strings can be shared because they are immutable.3 In C, string literals with the same characters can share one array.4 - Safe concurrent reads. The Python glossary calls immutable objects inherently thread-safe, because no thread can change their state after creation.1 In Java,
finalfields let a programmer write thread-safe immutable objects without synchronization.5 - Stable hash keys. A hash table finds a key by its hash value. That value must not change while the key is in the table. In Python, a hashable object has a hash value that never changes during its lifetime, and most immutable built-in objects are hashable.6 The C# documentation gives a hash code that stays the same in a hash table as one reason to use immutable records.7
- Local reasoning. A reader who sees an immutable value knows that no other code can change it. The Rust book gives the bug that this prevents. One part of the code assumes that a value never changes, and another part sometimes changes it.8
- No defensive copies. A function can keep an immutable argument as it is. It does not need to copy the argument to protect its own state.
How it works
A binding or a value
A binding links a name to a value. An immutable binding cannot get a different value by assignment, but the value that it names can still be mutable. A mutable binding can name an immutable value. The two ideas are independent.
Many languages give immutable bindings. In JavaScript, a const declaration makes a strict immutable binding.9 An assignment to such a binding throws TypeError, in strict code and in sloppy code.10 A Java final variable can be assigned only once.11 A Kotlin val is a read-only variable that cannot get a different value after initialization.12 A Rust let binding is immutable unless it has the keyword mut.8 The Bash builtin readonly marks names whose values cannot be changed by assignment or unset.13 In PowerShell, Set-Variable -Option ReadOnly makes a variable that cannot be changed without -Force. With -Option Constant, the variable cannot be changed or deleted.14
None of these bindings makes the value immutable. A JavaScript const array still accepts push (see Pitfalls).
A read-only view or an immutable object
A read-only view is a reference that has no operations that change the object. Other references to the same object can still change it. The C++ standard says that a const access path cannot change an object, even when another access path can change it.15 The Java collection documentation describes an unmodifiable view of a backing collection. Changes to the backing collection are visible through the view.16 ReadOnlyCollection<T> in .NET is a wrapper of the same kind.17 In Kotlin, each collection type has a read-only interface, such as List, and a mutable interface, such as MutableList. A read-only interface prevents changes only through that interface.18 A TypeScript readonly property can change through an alias of a type without readonly.19
An immutable object has no access path that changes it. In Java, List.of and List.copyOf return unmodifiable lists. Their mutator methods always throw UnsupportedOperationException.20 The Kotlin documentation makes the same distinction: an immutable collection does not allow changes to its elements after creation.18
Shallow or deep
Shallow immutability fixes the fields of one object. The objects that the fields refer to can still change. Deep immutability needs every object that is reachable from the value to be immutable too.
Most language features are shallow. A Python tuple that holds a list is still an immutable container, because the set of objects that it contains cannot change. Its value changes when the list changes.2 Object.freeze in JavaScript acts on the own properties of the object only, so an object inside it can still change.21 The init-only properties of a C# record have shallow immutability: the data that a reference-type property refers to can change.7 The Java documentation says that an unmodifiable collection is not necessarily immutable, because its elements can be mutable. An unmodifiable collection of immutable elements can be considered effectively immutable.16
Interior mutability
Some types change their internal state behind an interface that looks immutable. In Rust, a type has interior mutability when its internal state can change through a shared reference. UnsafeCell<T> is the only allowed way to do this, and types such as Cell<T> and RefCell<T> are built on it. RefCell<T> checks the borrow rules at run time.22 The std::cell documentation contrasts interior mutability with inherited mutability, where a value can change only through a unique &mut reference.23
In C++, a const member function sees this as a pointer to a const object.24 A member with the mutable specifier cancels the const of the object that contains it, so a const member function can change it.25 The C++ example uses a mutable counter in a const object.
Enforcement
A language can enforce immutability in three ways.
- At compile time. The compiler rejects the change. C and C++
const, Javafinal, Kotlinval, Rust bindings withoutmut, and C#readonlyfields work this way. In C#, areadonlyfield can be assigned only in its declaration or in a constructor of the same class.26 Aninitaccessor assigns a property only during object construction.27 TypeScript checksreadonlyat compile time only. The modifier does not change any behaviour at run time.19 - At run time. A check stops the change when it happens.
Object.freezemakes the properties of an object read-only, and later writes fail.28 A failed write throwsTypeErroronly in strict mode code. In sloppy mode, it does nothing and gives no error.29 A Python frozen dataclass raisesFrozenInstanceErroron an assignment to a field.30 A Java unmodifiable list throwsUnsupportedOperationExceptionfrom its mutator methods.20 - By convention. No check exists, and the programmer keeps the rule. The Python documentation says that it is not possible to create truly immutable Python objects;
frozen=Trueonly emulates immutability.30 Go has immutable strings,31 andconstdeclares boolean, rune, numeric and string constants only.32 For other Go types, the usual forms are unexported fields and copies (see the Go example).
The compile-time checks of C and C++ do not hold at run time. A cast can remove const. A change to an object that was defined const is undefined behaviour in C and in C++.3315 A change to a C string literal is also undefined behaviour.4 In the C example, AddressSanitizer stops such a write.
Persistent data structures and structural sharing
A change to an immutable collection gives a fresh collection. A full copy costs time and memory in proportion to the size. Persistent data structures avoid most of this cost.
Driscoll, Sarnak, Sleator and Tarjan describe ordinary data structures as ephemeral: a change destroys the old version. A persistent structure allows access to every version at any time. It is partially persistent when only the last version can change, and fully persistent when every version can change.34
The usual technique is structural sharing. The fresh version reuses the unchanged parts of the old version. In this stack, each cell is a tuple of a value and the rest of the stack. A push makes one fresh cell. The stacks b and c share all the cells of a.
def push(stack, value):
return (value, stack)
def to_list(stack):
values = []
while stack is not None:
value, stack = stack
values.append(value)
return values
a = push(push(None, 1), 2)
b = push(a, 3)
c = push(a, 4)
print(b[1] is a, c[1] is a)
print(to_list(a), to_list(b), to_list(c))
True True
[2, 1] [3, 2, 1] [4, 2, 1]
The old version stays valid because no cell ever changes. The four authors give general techniques that make linked data structures persistent. They use the techniques to make persistent binary search trees.34 The Kotlin documentation points to the kotlinx-collections-immutable library for immutable and persistent collections.18 In .NET, the namespace System.Collections.Immutable contains immutable collections.35
Copy-on-write
Copy-on-write lets several holders share one copy until one of them wants to change it. Then that holder gets its own copy, and the others keep the shared one. In Rust, Rc::make_mut gives a mutable reference to the value in an Rc. If other Rc pointers share the allocation, it first clones the value. The Rust documentation calls this clone-on-write.36
use std::rc::Rc;
fn main() {
let first = Rc::new(vec![1, 2, 3]);
let mut second = Rc::clone(&first);
println!("shared: {}", Rc::ptr_eq(&first, &second));
Rc::make_mut(&mut second).push(4);
println!("shared: {}", Rc::ptr_eq(&first, &second));
println!("{first:?} {second:?}");
}
shared: true
shared: false
[1, 2, 3] [1, 2, 3, 4]
Before the change, both pointers refer to one vector. The call to make_mut clones the vector, so first keeps the old value.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Standard library | |
| TypeScript | Native | |
| Go | Idiom | |
| Rust | Native | |
| Kotlin | Native | |
| SQL | Does not apply | A query has no objects that code shares and changes. |
| Bash | Native | The readonly builtin marks a variable, so a later assignment or unset fails. The protection belongs to the name. |
| PowerShell | Native | |
| HTML | Does not apply | Markup has no program values. |
| CSS | Does not apply | Style rules have no program values. |
| Regular expressions | Does not apply | A pattern has no values to change. |
The example files show the immutable forms of each language, and the matching read-only or shallow forms. The table gives the verdict for each tier 1 language.
| Language | Verdict | Form |
|---|---|---|
| Python | native | immutable built-in types such as str, tuple and frozenset; @dataclass(frozen=True) |
| JavaScript | native | immutable primitive values; const bindings; Object.freeze |
| TypeScript | native | readonly, ReadonlyArray<T> and as const, checked at compile time only |
| Java | native | final; records; List.of and List.copyOf |
| C | native | the const qualifier |
| C++ | native | const objects and member functions; constexpr; mutable |
| C# | native | readonly, init and records; System.Collections.Immutable |
| Go | idiom | immutable strings; const for basic types; copies for the rest |
| Rust | native | immutable bindings by default; mut; Cell and RefCell |
| Kotlin | native | val; read-only collection interfaces; copy of a data class |
| PowerShell | native | Set-Variable -Option ReadOnly or -Option Constant |
| Bash | native | the readonly builtin for variables |
| SQL | n/a | a query has no objects that code shares and changes |
| Regex | n/a | a pattern has no values to change |
| HTML/CSS | n/a | markup and style rules have no program values |
In TypeScript, as const makes the type checker give each property its literal type, as const does for a binding.37 Like readonly, it has no effect on the emitted JavaScript.
Bash has no example file. The readonly builtin marks a variable, so a later assignment or unset fails.13 The protection belongs to the name, as with const in JavaScript.
from dataclasses import FrozenInstanceError, dataclass, replace
@dataclass(frozen=True)
class Point:
x: int
y: int
p = Point(1, 2)
q = replace(p, y=5)
print(p, q)
try:
p.x = 9
except FrozenInstanceError as error:
print(type(error).__name__)
word = "abc"
print(word.upper(), word)
tags = frozenset({"a", "b"})
print(sorted(tags | {"c"}), sorted(tags))
print({(1, 2): "point"}[(1, 2)])
Point(x=1, y=2) Point(x=1, y=5)
FrozenInstanceError
ABC abc
['a', 'b', 'c'] ['a', 'b']
point
- Verdict: native. Numbers,
str,bytes,tupleandfrozensetare immutable types. An operation on them returns a fresh object. @dataclass(frozen=True)adds__setattr__and__delattr__methods that raiseFrozenInstanceError.dataclasses.replacereturns a changed copy.- The language has no keyword for a constant binding. Any name can get a different object by assignment.
- Immutability is shallow. A tuple can hold a list, and the list can change. Such a tuple is not hashable (see the pitfalls in the node).
#include <print>
#include <vector>
class Temperature {
public:
explicit Temperature(double celsius) : celsius_(celsius) {}
double fahrenheit() const {
++reads_;
return celsius_ * 9.0 / 5.0 + 32.0;
}
int reads() const { return reads_; }
private:
const double celsius_;
mutable int reads_ = 0;
};
int main() {
const Temperature t{100.0};
std::println("{} {}", t.fahrenheit(), t.fahrenheit());
std::println("{}", t.reads());
constexpr int cells = 4 * 4;
std::println("{}", cells);
const std::vector<int> v{1, 2, 3};
std::vector<int> w = v;
w.push_back(4);
std::println("{} {}", v.size(), w.size());
}
212 212
2
16
3 4
- Verdict: native.
constapplies to objects, references, pointers and member functions.constexprasks for a value at compile time. - In a
constmember function,thispoints to aconstobject, so the function cannot change ordinary members. - A
mutablemember can change even in aconstobject. The usual use is a cache or a counter that does not change the visible value. - A
constreference or pointer is a read-only access path. Another path can still change the object. - A change to an object that was defined
const, for example after aconst_cast, is undefined behaviour.
import java.util.ArrayList;
import java.util.List;
public class Main {
record Point(int x, int y) {
Point withY(int newY) {
return new Point(x, newY);
}
}
public static void main(String[] args) {
Point p = new Point(1, 2);
System.out.println(p + " " + p.withY(5));
List<String> source = new ArrayList<>(List.of("a", "b"));
List<String> copy = List.copyOf(source);
source.add("c");
System.out.println(source + " " + copy);
String word = "abc";
System.out.println(word.toUpperCase() + " " + word);
}
}
Point[x=1, y=2] Point[x=1, y=5]
[a, b, c] [a, b]
ABC abc
- Verdict: native. A
finalvariable or field gets one value. The fields of a record areprivate final.Stringobjects cannot change. List.ofandList.copyOfreturn unmodifiable lists.List.copyOfcopies, so later changes to the source do not show in the copy.- An unmodifiable list has the type
List, so a call toaddcompiles. It throwsUnsupportedOperationExceptionat run time. Collections.unmodifiableListreturns a view. Changes to the backing list show through the view (see the pitfalls in the node).- A
finalfield that holds a mutable object only fixes the reference.
#include <stdio.h>
struct point {
int x;
int y;
};
static int sum(const int *values, size_t n) {
int total = 0;
for (size_t i = 0; i < n; i++) {
total += values[i];
}
return total;
}
int main(void) {
const struct point p = {1, 2};
struct point q = p;
q.y = 5;
printf("%d %d, %d %d\n", p.x, p.y, q.x, q.y);
int data[] = {1, 2, 3};
printf("%d\n", sum(data, 3));
char copy[] = "abc";
copy[0] = 'X';
printf("%s\n", copy);
}
1 2, 1 5
6
Xbc
- Verdict: native. The
constqualifier makes an object read-only. The compiler rejects an assignment through aconstlvalue. - A
const int *parameter promises that the function does not change the data through that pointer. The caller's array itself need not beconst. - A cast can remove
const. A change to an object that was definedconstis then undefined behaviour. - A change to a string literal is undefined behaviour.
char copy[] = "abc"makes a changeable array copy. A pointer to the literal does not:
This code has a memory error, on purpose, and the sanitizer reports it.
#include <stdio.h>
int main(void) {
char *text = "abc";
text[0] = 'X';
printf("%s\n", text);
}
In this run, AddressSanitizer stops the program with BUS on unknown address. Without the sanitizer, the behaviour is still undefined.
using System.Collections.Immutable;
using System.Collections.ObjectModel;
var p = new Point(1, 2);
var q = p with { Y = 5 };
Console.WriteLine($"{p} {q}");
var source = new List<int> { 1, 2 };
var view = new ReadOnlyCollection<int>(source);
var frozen = ImmutableList.CreateRange(source);
source.Add(3);
Console.WriteLine($"{view.Count} {frozen.Count}");
var more = frozen.Add(4);
Console.WriteLine($"{frozen.Count} {more.Count}");
record Point(int X, int Y);
Point { X = 1, Y = 2 } Point { X = 1, Y = 5 }
3 2
2 3
- Verdict: native.
readonlyfields,initaccessors and records give immutability that the compiler checks. - A positional record class has init-only properties. A
withexpression makes a copy with some properties changed. - The immutability is shallow. A
readonlyfield or an init-only property that holds aList<T>fixes only the reference. ReadOnlyCollection<T>is a wrapper. Changes to the wrapped list show through it, as the count 3 shows.System.Collections.Immutablehas immutable collections.Addreturns a fresh collection and leaves the original as it was.
"use strict";
const point = Object.freeze({ x: 1, y: 2 });
try {
point.x = 9;
} catch (error) {
console.log(error.constructor.name);
}
console.log(point.x, Object.isFrozen(point));
const moved = { ...point, y: 5 };
console.log(moved);
const numbers = [3, 1, 2];
console.log(numbers.toSorted(), numbers);
const word = "abc";
console.log(word.toUpperCase(), word);
TypeError
1 true
{ x: 1, y: 5 }
[ 1, 2, 3 ] [ 3, 1, 2 ]
ABC abc
- Verdict: stdlib. Strings and the other primitive values cannot change.
Object.freezemakes the own properties of an object read-only and stops the addition of properties. - In strict code, an assignment to a frozen property throws
TypeError. In sloppy code, the assignment does nothing and gives no error. Object.freezeis shallow. An object inside a frozen object can still change.constmakes the binding immutable, not the value. Aconstarray acceptspush.- Spread syntax and methods such as
toSortedmake a changed copy and leave the original as it was.
interface Point {
readonly x: number;
readonly y: number;
}
const p: Point = { x: 1, y: 2 };
const moved: Point = { ...p, y: 5 };
console.log(p, moved);
const names: ReadonlyArray<string> = ["grace", "ada"];
const sorted = [...names].sort();
console.log(sorted, names);
const settings = { mode: "strict" } as const;
console.log(settings.mode);
{ x: 1, y: 2 } { x: 1, y: 5 }
[ 'ada', 'grace' ] [ 'grace', 'ada' ]
strict
- Verdict: native.
readonlyproperties,ReadonlyArray<T>andas constare checks of the type checker. An assignment top.xis the error TS2540, "Cannot assign to 'x' because it is a read-only property". - The checks have no effect at run time. The emitted JavaScript can still change the object. Use
Object.freezefor a run-time guard. - A
readonlytype does not stop a change through a writable alias, because the checker ignoresreadonlywhen it compares two types:
This code runs but gives a wrong answer on purpose.
interface Person {
name: string;
age: number;
}
interface ReadonlyPerson {
readonly name: string;
readonly age: number;
}
const writable: Person = { name: "Ada", age: 36 };
const view: ReadonlyPerson = writable;
writable.age++;
console.log(view.age);
37
package main
import (
"fmt"
"slices"
)
type Point struct{ X, Y int }
func main() {
word := "abc"
bytes := []byte(word)
bytes[0] = 'X'
fmt.Println(word, string(bytes))
p := Point{1, 2}
q := p
q.Y = 5
fmt.Println(p, q)
numbers := []int{1, 2, 3}
alias := numbers
alias[0] = 9
clone := slices.Clone(numbers)
clone[1] = 0
fmt.Println(numbers, clone)
}
abc Xbc
{1 2} {1 5}
[9 2 3] [9 0 3]
- Verdict: idiom. Strings are immutable.
constdeclares constants of boolean, numeric and string types only. - There is no read-only struct, slice or map. The usual form is a value copy, an unexported field with getter methods, or a copy that a function returns.
- An assignment copies a struct value. An assignment of a slice copies only the slice header, so both slices share one array.
slices.Clonemakes a separate array. - The conversion of a string to
[]bytemakes a fresh array, so a change to the bytes does not change the string.
use std::cell::Cell;
fn main() {
let v = vec![1, 2, 3];
let mut w = v.clone();
w.push(4);
println!("{v:?} {w:?}");
let hits = Cell::new(0);
let first = &hits;
let second = &hits;
first.set(first.get() + 1);
second.set(second.get() + 1);
println!("{}", hits.get());
}
[1, 2, 3] [1, 2, 3, 4]
2
- Verdict: native. A
letbinding is immutable unless it hasmut. A shared reference&Tstops changes to the value while the reference exists. - Mutability belongs to the binding and the reference, not to the type. The same
Vecis immutable throughvand mutable throughw. Cell,RefCelland the atomic types give interior mutability: a change through a shared reference.UnsafeCellis the only base for this.- A mutable borrow of an immutable binding is the error E0596:
This code does not compile, on purpose.
fn main() {
let v = vec![1, 2, 3];
let r = &mut v;
r.push(4);
println!("{r:?}");
}
rustc stops with cannot borrow `v` as mutable, as it is not declared as mutable. The fix is let mut v.
data class Point(val x: Int, val y: Int)
fun main() {
val p = Point(1, 2)
val q = p.copy(y = 5)
println("$p $q")
val names: List<String> = listOf("ada", "alan")
val more = names + "grace"
println("$names $more")
val source = mutableListOf(1, 2)
val view: List<Int> = source
source.add(3)
println(view)
}
Point(x=1, y=2) Point(x=1, y=5)
[ada, alan] [ada, alan, grace]
[1, 2, 3]
- Verdict: native. A
valis assigned only once. Avarcan be assigned again. - Each collection type has a read-only interface, such as
List, and a mutable interface, such asMutableList. A read-only interface has no operations that add, remove or update elements. - A read-only interface is not an immutable collection. Here
viewhas the typeList<Int>, and it shows the element thatsourceadded. - The
copyfunction of a data class makes a copy with some properties changed. The+operator on aListreturns a fresh list. - An assignment to a
valis a compile error:
This code does not compile, on purpose.
fun main() {
val count = 0
count = 1
println(count)
}
kotlinc stops with 'val' cannot be reassigned.
Set-Variable -Name Limit -Value 10 -Option ReadOnly
try {
$Limit = 20
} catch {
Write-Output $_.Exception.GetType().Name
}
Write-Output $Limit
Set-Variable -Name Limit -Value 30 -Force
Write-Output $Limit
Set-Variable -Name Items -Value ([System.Collections.ArrayList]@(1, 2)) -Option Constant
[void]$Items.Add(3)
Write-Output $Items.Count
SessionStateUnauthorizedAccessException
10
30
3
- Verdict: native.
Set-Variable -Option ReadOnlymakes a variable that a plain assignment cannot change. The-Forceparameter can still change it, and the variable can be deleted. -Option Constantmakes a variable that cannot be changed or deleted. The option is valid only when the variable is created.- Both options protect the variable, not the object in it. Here the constant
$Itemsholds anArrayList, andAddstill changes the list. - .NET immutable types, such as
stringand the types inSystem.Collections.Immutable, give immutable values.
Variations and related ideas
- Value semantics. When an assignment copies the value, each holder has its own copy. A change by one holder is not visible to the others. Go and C copy a struct on assignment, as the examples show. Pointers and references describes the other case, where holders share one object.
- Value types and reference types. In C#, a
readonlyfield of a value type is immutable. Areadonlyfield of a reference type always refers to the same object, but that object can still change.26 - Constants. A constant gets its value from a literal or a constant expression. Go constants are an example.32 C++
constexprvariables are another (see the C++ example). A constant is a stricter form of an immutable binding. - Nondestructive update. A copy with some fields changed takes the place of a change. C# has the
withexpression for records.7 Kotlin data classes havecopy.38 Python hasdataclasses.replace.30 JavaScript has spread syntax. - Freeze after build. A program builds a value with a mutable object, and then gives out an immutable copy.
List.copyOfin Java andImmutableList.CreateRangein C# make such a copy.2035 - Borrowing. Rust does not forbid all change. It forbids a direct change while a shared reference to the value exists.39 A program can change a value when it holds the only reference.
- Closures. A closure that captures only immutable values gives the same result each time its captures are read. Closure describes captures that change.
Pitfalls
A const binding does not freeze the value
A JavaScript const declaration makes the binding immutable.9 The array that it names is still mutable.
This code runs but gives a wrong answer on purpose.
const items = [1, 2];
items.push(3);
console.log(items);
[ 1, 2, 3 ]
Use Object.freeze(items) when the array must not change. Use a copy such as [...items, 3] when the program needs a changed array.
Object.freeze is shallow
Object.freeze acts on the own properties of the object.21 An array or an object in a property can still change. In sloppy mode code, a write to a frozen property also fails with no error.29
This code runs but gives a wrong answer on purpose.
const config = Object.freeze({ name: "app", tags: ["a"] });
config.tags.push("b");
config.name = "other";
console.log(config.name, config.tags, Object.isFrozen(config));
app [ 'a', 'b' ] true
The array in tags changed, and the write to name was lost without a message. The fix is a function that also freezes each nested object. The directive "use strict" turns the lost write into a TypeError (see the JavaScript example).
An unmodifiable view shows changes to the original
Collections.unmodifiableList returns a view. Its mutator methods throw, but changes to the backing list are visible through it.16
This code runs but gives a wrong answer on purpose.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> source = new ArrayList<>(List.of("a"));
List<String> view = Collections.unmodifiableList(source);
source.add("b");
System.out.println(view);
}
}
[a, b]
A class that gives out such a view of an internal list still lets its own code change the list. When the caller must see a fixed value, use List.copyOf(source), which copies.20 C# ReadOnlyCollection<T> and Kotlin read-only interfaces behave the same way.1718
An unmodifiable list fails only at run time
The lists that List.of returns have the type List, which has the method add. JEP 269 states that it does not try to show unmodifiability in the type system.40 So the call compiles, and it fails when it runs.20
This code raises UnsupportedOperationException, on purpose.
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> names = List.of("ada", "alan");
names.add("grace");
System.out.println(names);
}
}
The run stops with java.lang.UnsupportedOperationException, with no message. A method that receives a List cannot know from the type whether add works. Write in the documentation of a method when it returns an unmodifiable list. Make a mutable copy with new ArrayList<>(names) when a change is necessary.
A tuple that holds a list
A Python tuple is immutable, but a list in it is not. The tuple is hashable only when all its elements are hashable, so it cannot be a dictionary key.6
This code raises TypeError, on purpose.
key = (1, [2, 3])
cache = {key: "value"}
print(cache)
The run stops with TypeError: cannot use 'tuple' as a dict key (unhashable type: 'list'). Use a tuple of immutable elements, such as (1, (2, 3)), as the key.
An augmented assignment to such an element both raises an error and changes the list. t[1] += [4] first calls the list's in-place addition, which changes the list. Then it assigns the result to t[1], and the tuple rejects the assignment.41
This code runs but gives a wrong answer on purpose.
t = (1, [2, 3])
try:
t[1] += [4]
except TypeError as error:
print("TypeError:", error)
print(t)
TypeError: 'tuple' object does not support item assignment
(1, [2, 3, 4])
The fix is a method call on the list, t[1].append(4) or t[1].extend([4]), which does not assign to the tuple.
An assignment to an immutable Rust binding
A Rust let binding without mut cannot get a second value.8
This code does not compile, on purpose.
fn main() {
let count = 0;
count += 1;
println!("{count}");
}
rustc stops with error E0384, cannot assign twice to immutable variable.42 The fix is let mut count = 0;, or a fresh binding such as let count = count + 1;, which shadows the first one.
A read-only interface is not an immutable list
A Kotlin function that takes a List cannot change the list through that interface.18 But a List value can be a MutableList at run time. A cast gets the mutable interface back, and the change reaches the caller's list.
This code runs but gives a wrong answer on purpose.
fun register(names: List<String>) {
(names as MutableList<String>).add("grace")
}
fun main() {
val team = mutableListOf("ada", "alan")
register(team)
println(team)
}
[ada, alan, grace]
The caller gave a read-only view, and the function changed the list. Give out a copy, such as team.toList(), when the caller must keep its list as it is.
Cost
- A fresh object for each change. A change to an immutable value makes a fresh object. A loop that builds a value from many changes makes many objects. Mutable builders avoid this. The Java
Stringdocumentation names string buffers as the mutable form of strings.3 - Persistent structures. Structural sharing avoids a full copy for each change. Driscoll, Sarnak, Sleator and Tarjan give persistent binary search trees with logarithmic time for access, insertion and deletion. Each insertion and deletion takes constant space.34
- Run-time checks. A frozen Python dataclass has a small cost: its
__init__must callobject.__setattr__to set the fields, not a plain assignment.30 - Compile-time checks. TypeScript
readonlyhas no cost at run time, because it does not change the emitted code. For the same reason, it gives no protection at run time.19 - Optimization. A Java compiler can keep the value of a
finalfield in a register. A field that is notfinalmust be read again in some of these places.5 - Copy-on-write.
Rc::make_mutclones only when other pointers share the value. A value with one owner changes in place.36
History
- 1986 and 1989. Driscoll, Sarnak, Sleator and Tarjan studied persistent data structures. They presented a first version at the ACM Symposium on Theory of Computing in 1986, and the journal version appeared in 1989.34
- 2017. JDK 9 reached General Availability on 21 September 2017.43 It added the factory methods
List.of,Set.ofandMap.of, which return unmodifiable collections (JEP 269).40 - 2018. Python 3.7 was released on 27 June 2018.44 It added the
dataclassesmodule of PEP 557, with the parameterfrozen.45 - 2020. C# 9 was released in November 2020, with records and init-only setters.46
- 2021. JDK 16 reached General Availability on 16 March 2021.47 It made records a final feature of Java. JEP 395 describes them as classes that act as transparent carriers for immutable data.48
References
- Python Glossary, Python 3.14, immutable
- The Python Language Reference, Data model, Python 3.14, 3.1 Objects, values and types
- Java SE 25 API, java.lang.String, class description
- N1570, Committee Draft of ISO/IEC 9899:2011 (C11), 6.4.5 String literals, paragraph 7
- The Java Language Specification, Java SE 25 Edition, 17.5 final Field Semantics
- Python Glossary, Python 3.14, hashable
- C# language reference, Records, Immutability; Nondestructive mutation
- The Rust Programming Language, 3.1 Variables and Mutability
- ECMA-262, ECMAScript 2026 Language Specification, 14.2.3 BlockDeclarationInstantiation
- ECMA-262, ECMAScript 2026 Language Specification, 9.1.1.1.5 SetMutableBinding
- The Java Language Specification, Java SE 25 Edition, 4.12.4 final Variables
- Kotlin documentation, Basic syntax, Variables
- Bash Reference Manual, 4.1 Bourne Shell Builtins, readonly
- PowerShell documentation, Set-Variable, parameters -Option and -Force
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [dcl.type.cv], paragraphs 3 and 4
- Java SE 25 API, java.util.Collection, Unmodifiable Collections; Unmodifiable View Collections
- .NET API, ReadOnlyCollection<T> Class, Remarks
- Kotlin documentation, Collections overview, Read-only and mutable collections
- TypeScript Handbook, Object Types, readonly Properties; The ReadonlyArray Type
- Java SE 25 API, java.util.List, Unmodifiable Lists
- ECMA-262, ECMAScript 2026 Language Specification, 7.3.15 SetIntegrityLevel
- The Rust Reference, Interior mutability, rules interior-mut.shared-ref, interior-mut.unsafe-cell and interior-mut.ref-cell
- The Rust Standard Library, module std::cell, module description
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [expr.prim.this], paragraph 3
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [dcl.stc], paragraph 9, note 5
- C# language reference, readonly, the field declaration context
- C# language reference, init, introduction
- ECMA-262, ECMAScript 2026 Language Specification, 20.1.2.6 Object.freeze
- ECMA-262, ECMAScript 2026 Language Specification, 6.2.5.6 PutValue
- Python Standard Library, dataclasses, Python 3.14, Frozen instances
- The Go Programming Language Specification, String types
- The Go Programming Language Specification, Constants
- N1570, Committee Draft of ISO/IEC 9899:2011 (C11), 6.7.3 Type qualifiers, paragraph 6
- James R. Driscoll, Neil Sarnak, Daniel D. Sleator and Robert E. Tarjan, Making data structures persistent, Journal of Computer and System Sciences 38(1), 1989, pp. 86-124, the abstract on p. 86, the definitions of persistence in Section 1 on p. 87, and the footnote on p. 86 about the 1986 preliminary version
- .NET API, System.Collections.Immutable Namespace, namespace description
- The Rust Standard Library, std::rc::Rc, method make_mut
- TypeScript Handbook, Everyday Types, Literal Inference, the as const suffix
- Kotlin documentation, Data classes, Copying
- The Rust Reference, Pointer types, rule type.pointer.reference.shared.constraint-mutation
- JEP 269, Convenience Factory Methods for Collections, header (Release 9); Goals; Non-Goals
- Python Programming FAQ, Python 3.14, Why does a_tuple[i] += ['item'] raise an exception when the addition works?
- Rust error codes index, E0384
- OpenJDK, JDK 9, introduction and schedule (General Availability on 21 September 2017)
- Python Release Python 3.7.0, release date
- PEP 557, Data Classes, header (Python-Version 3.7); Specification, the frozen parameter
- The history of C#, C# version 9
- OpenJDK, JDK 16, introduction and schedule (General Availability on 16 March 2021)
- JEP 395, Records, header (Release 16); Summary
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag T6YGYP Edit this page History Report an error Markdown