Programming Search⌘K

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)
Output
[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)
Output
(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 String class 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, final fields 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, Java final, Kotlin val, Rust bindings without mut, and C# readonly fields work this way. In C#, a readonly field can be assigned only in its declaration or in a constructor of the same class.26 An init accessor assigns a property only during object construction.27 TypeScript checks readonly at 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.freeze makes the properties of an object read-only, and later writes fail.28 A failed write throws TypeError only in strict mode code. In sloppy mode, it does nothing and gives no error.29 A Python frozen dataclass raises FrozenInstanceError on an assignment to a field.30 A Java unmodifiable list throws UnsupportedOperationException from 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=True only emulates immutability.30 Go has immutable strings,31 and const declares 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))
Output
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:?}");
}
Output
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

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptStandard library
TypeScriptNative
GoIdiom
RustNative
KotlinNative
SQLDoes not applyA query has no objects that code shares and changes.
BashNativeThe readonly builtin marks a variable, so a later assignment or unset fails. The protection belongs to the name.
PowerShellNative
HTMLDoes not applyMarkup has no program values.
CSSDoes not applyStyle rules have no program values.
Regular expressionsDoes not applyA 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.

PythonGitHub
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)])
Output
Point(x=1, y=2) Point(x=1, y=5)
FrozenInstanceError
ABC abc
['a', 'b', 'c'] ['a', 'b']
point
  • Verdict: native. Numbers, str, bytes, tuple and frozenset are immutable types. An operation on them returns a fresh object.
  • @dataclass(frozen=True) adds __setattr__ and __delattr__ methods that raise FrozenInstanceError. dataclasses.replace returns 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());
}
Output
212 212
2
16
3 4
  • Verdict: native. const applies to objects, references, pointers and member functions. constexpr asks for a value at compile time.
  • In a const member function, this points to a const object, so the function cannot change ordinary members.
  • A mutable member can change even in a const object. The usual use is a cache or a counter that does not change the visible value.
  • A const reference 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 a const_cast, is undefined behaviour.
JavaGitHub
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);
    }
}
Output
Point[x=1, y=2] Point[x=1, y=5]
[a, b, c] [a, b]
ABC abc
  • Verdict: native. A final variable or field gets one value. The fields of a record are private final. String objects cannot change.
  • List.of and List.copyOf return unmodifiable lists. List.copyOf copies, so later changes to the source do not show in the copy.
  • An unmodifiable list has the type List, so a call to add compiles. It throws UnsupportedOperationException at run time.
  • Collections.unmodifiableList returns a view. Changes to the backing list show through the view (see the pitfalls in the node).
  • A final field 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);
}
Output
1 2, 1 5
6
Xbc
  • Verdict: native. The const qualifier makes an object read-only. The compiler rejects an assignment through a const lvalue.
  • A const int * parameter promises that the function does not change the data through that pointer. The caller's array itself need not be const.
  • A cast can remove const. A change to an object that was defined const is 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);
Output
Point { X = 1, Y = 2 } Point { X = 1, Y = 5 }
3 2
2 3
  • Verdict: native. readonly fields, init accessors and records give immutability that the compiler checks.
  • A positional record class has init-only properties. A with expression makes a copy with some properties changed.
  • The immutability is shallow. A readonly field or an init-only property that holds a List<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.Immutable has immutable collections. Add returns a fresh collection and leaves the original as it was.
JavaScriptGitHub
"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);
Output
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.freeze makes 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.freeze is shallow. An object inside a frozen object can still change.
  • const makes the binding immutable, not the value. A const array accepts push.
  • Spread syntax and methods such as toSorted make a changed copy and leave the original as it was.
TypeScriptGitHub
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);
Output
{ x: 1, y: 2 } { x: 1, y: 5 }
[ 'ada', 'grace' ] [ 'grace', 'ada' ]
strict
  • Verdict: native. readonly properties, ReadonlyArray<T> and as const are checks of the type checker. An assignment to p.x is 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.freeze for a run-time guard.
  • A readonly type does not stop a change through a writable alias, because the checker ignores readonly when 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);
Output
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)
}
Output
abc Xbc
{1 2} {1 5}
[9 2 3] [9 0 3]
  • Verdict: idiom. Strings are immutable. const declares 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.Clone makes a separate array.
  • The conversion of a string to []byte makes a fresh array, so a change to the bytes does not change the string.
RustGitHub
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());
}
Output
[1, 2, 3] [1, 2, 3, 4]
2
  • Verdict: native. A let binding is immutable unless it has mut. A shared reference &T stops changes to the value while the reference exists.
  • Mutability belongs to the binding and the reference, not to the type. The same Vec is immutable through v and mutable through w.
  • Cell, RefCell and the atomic types give interior mutability: a change through a shared reference. UnsafeCell is 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.

KotlinGitHub
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)
}
Output
Point(x=1, y=2) Point(x=1, y=5)
[ada, alan] [ada, alan, grace]
[1, 2, 3]
  • Verdict: native. A val is assigned only once. A var can be assigned again.
  • Each collection type has a read-only interface, such as List, and a mutable interface, such as MutableList. A read-only interface has no operations that add, remove or update elements.
  • A read-only interface is not an immutable collection. Here view has the type List<Int>, and it shows the element that source added.
  • The copy function of a data class makes a copy with some properties changed. The + operator on a List returns a fresh list.
  • An assignment to a val is 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.

PowerShellGitHub
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
Output
SessionStateUnauthorizedAccessException
10
30
3
  • Verdict: native. Set-Variable -Option ReadOnly makes a variable that a plain assignment cannot change. The -Force parameter can still change it, and the variable can be deleted.
  • -Option Constant makes 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 $Items holds an ArrayList, and Add still changes the list.
  • .NET immutable types, such as string and the types in System.Collections.Immutable, give immutable values.
  • 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 readonly field of a value type is immutable. A readonly field 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++ constexpr variables 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 with expression for records.7 Kotlin data classes have copy.38 Python has dataclasses.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.copyOf in Java and ImmutableList.CreateRange in 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);
Output
[ 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));
Output
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);
    }
}
Output
[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)
Output
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)
}
Output
[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 String documentation 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 call object.__setattr__ to set the fields, not a plain assignment.30
  • Compile-time checks. TypeScript readonly has 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 final field in a register. A field that is not final must be read again in some of these places.5
  • Copy-on-write. Rc::make_mut clones 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.of and Map.of, which return unmodifiable collections (JEP 269).40
  • 2018. Python 3.7 was released on 27 June 2018.44 It added the dataclasses module of PEP 557, with the parameter frozen.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

  1. Python Glossary, Python 3.14, immutable
  2. The Python Language Reference, Data model, Python 3.14, 3.1 Objects, values and types
  3. Java SE 25 API, java.lang.String, class description
  4. N1570, Committee Draft of ISO/IEC 9899:2011 (C11), 6.4.5 String literals, paragraph 7
  5. The Java Language Specification, Java SE 25 Edition, 17.5 final Field Semantics
  6. Python Glossary, Python 3.14, hashable
  7. C# language reference, Records, Immutability; Nondestructive mutation
  8. The Rust Programming Language, 3.1 Variables and Mutability
  9. ECMA-262, ECMAScript 2026 Language Specification, 14.2.3 BlockDeclarationInstantiation
  10. ECMA-262, ECMAScript 2026 Language Specification, 9.1.1.1.5 SetMutableBinding
  11. The Java Language Specification, Java SE 25 Edition, 4.12.4 final Variables
  12. Kotlin documentation, Basic syntax, Variables
  13. Bash Reference Manual, 4.1 Bourne Shell Builtins, readonly
  14. PowerShell documentation, Set-Variable, parameters -Option and -Force
  15. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [dcl.type.cv], paragraphs 3 and 4
  16. Java SE 25 API, java.util.Collection, Unmodifiable Collections; Unmodifiable View Collections
  17. .NET API, ReadOnlyCollection<T> Class, Remarks
  18. Kotlin documentation, Collections overview, Read-only and mutable collections
  19. TypeScript Handbook, Object Types, readonly Properties; The ReadonlyArray Type
  20. Java SE 25 API, java.util.List, Unmodifiable Lists
  21. ECMA-262, ECMAScript 2026 Language Specification, 7.3.15 SetIntegrityLevel
  22. The Rust Reference, Interior mutability, rules interior-mut.shared-ref, interior-mut.unsafe-cell and interior-mut.ref-cell
  23. The Rust Standard Library, module std::cell, module description
  24. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [expr.prim.this], paragraph 3
  25. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [dcl.stc], paragraph 9, note 5
  26. C# language reference, readonly, the field declaration context
  27. C# language reference, init, introduction
  28. ECMA-262, ECMAScript 2026 Language Specification, 20.1.2.6 Object.freeze
  29. ECMA-262, ECMAScript 2026 Language Specification, 6.2.5.6 PutValue
  30. Python Standard Library, dataclasses, Python 3.14, Frozen instances
  31. The Go Programming Language Specification, String types
  32. The Go Programming Language Specification, Constants
  33. N1570, Committee Draft of ISO/IEC 9899:2011 (C11), 6.7.3 Type qualifiers, paragraph 6
  34. 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
  35. .NET API, System.Collections.Immutable Namespace, namespace description
  36. The Rust Standard Library, std::rc::Rc, method make_mut
  37. TypeScript Handbook, Everyday Types, Literal Inference, the as const suffix
  38. Kotlin documentation, Data classes, Copying
  39. The Rust Reference, Pointer types, rule type.pointer.reference.shared.constraint-mutation
  40. JEP 269, Convenience Factory Methods for Collections, header (Release 9); Goals; Non-Goals
  41. Python Programming FAQ, Python 3.14, Why does a_tuple[i] += ['item'] raise an exception when the addition works?
  42. Rust error codes index, E0384
  43. OpenJDK, JDK 9, introduction and schedule (General Availability on 21 September 2017)
  44. Python Release Python 3.7.0, release date
  45. PEP 557, Data Classes, header (Python-Version 3.7); Specification, the frozen parameter
  46. The history of C#, C# version 9
  47. OpenJDK, JDK 16, introduction and schedule (General Availability on 16 March 2021)
  48. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/T6YGYP/text.yaml