{
  "id": "enwiki-001333190200",
  "slug": "immutable-object",
  "title": "Immutable object",
  "qid": "",
  "lead": "In object-oriented (OO) and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created. This is in contrast to a mutable object (changeable object), which can be modified after it is created. In some cases, an object is considered immutable even if some internally used attributes change, but the object's state appears unchanging from an external point of view. For example, an object that uses to cache the results of expensive computations could still be considered an immutable object. Strings and other concrete objects are typically expressed as immutable objects to improve readability and runtime efficiency in object-oriented programming. Immutable objects are also useful because they are inherently thread-safe. Other benefits are that they are simpler to understand and reason about and offer higher security than mutable objects.",
  "body": "In object-oriented (OO) and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created. This is in contrast to a mutable object (changeable object), which can be modified after it is created. In some cases, an object is considered immutable even if some internally used attributes change, but the object's state appears unchanging from an external point of view. For example, an object that uses to cache the results of expensive computations could still be considered an immutable object. Strings and other concrete objects are typically expressed as immutable objects to improve readability and runtime efficiency in object-oriented programming. Immutable objects are also useful because they are inherently thread-safe. Other benefits are that they are simpler to understand and reason about and offer higher security than mutable objects. type Some_type is new Integer; -- could be anything more complicated x: constant Some_type:= 1; -- immutable y: Some_type; -- mutable Subprogram parameters are immutable in the in mode, and mutable in the in out and out modes. procedure Do_it(a: in Integer; b: in out Integer; c: out Integer) is begin -- a is immutable b:= b + a; c:= a; end Do_it; class ImmutableType { public readonly double Value { get; } public ImmutableType(double x) { Value = x; } public ImmutableType Square() { return new ImmutableType(Value * Value); } } C# has records which are immutable. record Person(string FirstName, string LastName); import std; using std::vector; using std::views::transform; class ShoppingCart { private: vector items; public: explicit Cart(const vector & items): items{items} {} vector & items() { return items; } const vector & items() const { return items; } double computeTotalCost() const { return std::ranges::accumulate( items | transform([](const Merchandise& m) -> double { return m.getPrice(); }), 0.0 ); } }; Note that, when there is a data member that is a pointer or reference to another object, then it is possible to mutate the object pointed to or referenced only within a non-const method. C++ also provides abstract (as opposed to bitwise) immutability via the mutable keyword, which lets a member variable be changed from within a const method. import std; using std::optional; using std::vector; using std::views::transform; class ShoppingCart { private: vector items; mutable optional totalCost; public: explicit Cart(const vector & items): items{items} {} const vector & items() const { return items; } int computeTotalCost() const { if (!totalCost) { totalCost = std::ranges::accumulate( items | transform([](const Merchandise& m) -> double { return m.getPrice(); }), 0.0 ); } return *totalCost; } }; class Example { Object mutableField; // mutable const Object constField; immutable Object immutableField; } For a mutable Example object, its mutableField can be written to. For a const(Example) object, mutableField cannot be modified, it inherits const ; immutableField is still immutable as it is the stronger guarantee. For an immutable(Example) , all fields are immutable. In a function like this: void fn(Example m, const Example c, immutable Example i) { // inside the braces } Inside the braces, c might refer to the same object as m , so mutations to m could indirectly change c as well. Also, c might refer to the same object as i , but since the value then is immutable, there are no changes. However, m and i cannot legally refer to the same object. In the language of guarantees, mutable has no guarantees (the function might change the object), const is an outward-only guarantee that the function will not change anything, and immutable is a bidirectional guarantee (the function will not change the value and the caller must not change it). Values that are const or immutable must be initialized by direct assignment at the point of declaration or by a constructor. Because const parameters forget if the value was mutable or not, a similar construct, inout , acts, in a sense, as a variable for mutability information. A function of type const(S) function(const(T)) returns const(S) typed values for mutable, const and immutable arguments. In contrast, a function of type inout(S) function(inout(T)) returns S for mutable T arguments, const(S) for const(T) values, and immutable(S) for immutable(T) values. Casting immutable values to mutable inflicts undefined behavior upon change, even if the original value comes from a mutable origin. Casting mutable values to immutable can be legal when there remain no mutable references afterward. \"An expression may be converted from mutable (...) to immutable if the expression is unique and all expressions it transitively refers to are either unique or immutable.\" If the compiler cannot prove uniqueness, the casting can be done explicitly and it is up to the programmer to ensure that no mutable references exist. The type string is an alias for immutable(char)[] , i.e. a typed slice of memory of immutable characters. Making substrings is cheap, as it just copies and modifies a pointer and a length filed, and safe, as the underlying data cannot be changed. Objects of type const(char)[] can refer to strings, but also to mutable buffers. Making a shallow copy of a const or immutable value removes the outer layer of immutability: Copying an immutable string ( immutable(char[]) ) returns a string ( immutable(char)[] ). The immutable pointer and length are being copied and the copies are mutable. The referred data has not been copied and keeps its qualifier, in the example immutable . It can be stripped by making a depper copy, e.g. using the dup function. String s = \"ABC\"; s.toLowerCase(); // This accomplishes nothing! The method toLowerCase() does not change the data \"ABC\" that s contains. Instead, a new String object is instantiated and given the data \"abc\" during its construction. A reference to this String object is returned by the toLowerCase() method. To make the String s contain the data \"abc\", a different approach is needed: s = s.toLowerCase(); Now the String s references a new String object that contains \"abc\". There is nothing in the syntax of the declaration of the class String that enforces it as immutable; rather, none of the String class's methods ever affect the data that a String object contains, thus making it immutable. The keyword final (detailed article) is used in implementing immutable primitive types and object references, but it cannot, by itself, make the objects themselves immutable. See below examples: Primitive type variables ( int , long , short , etc.) can be reassigned after being defined. This can be prevented by using final . int i = 42; //int is a primitive type i = 43; // OK final int j = 42; j = 43; // does not compile. j is final so can't be reassigned Reference types cannot be made immutable just by using the final keyword. final only prevents reassignment. final MyObject m = new MyObject(); //m is of reference type m.data = 100; // OK. We can change state of object m (m is mutable and final doesn't change this fact) m = new MyObject(); // does not compile. m is final so can't be reassigned Primitive wrappers ( Integer , Long , Short , Double , Float , Character , Byte , Boolean ) are also all immutable. Immutable classes can be implemented by following a few simple guidelines. function doSomething(x) { /* does changing x here change the original? */ }; var str = 'a string'; var obj = { an: 'object' }; doSomething(str); // strings, numbers and bool types are immutable, function gets a copy doSomething(obj); // objects are passed in by reference and are mutable inside function doAnotherThing(str, obj); // `str` has not changed, but `obj` may have. To simulate immutability in an object, one may define properties as read-only (writable: false). var obj = {}; Object.defineProperty(obj, 'foo', { value: 'bar', writable: false }); obj.foo = 'bar2'; // silently ignored However, the approach above still lets new properties be added. Alternatively, one may use Object.freeze to make existing objects immutable. var obj = { foo: 'bar' }; Object.freeze(obj); obj.foo = 'bars'; // cannot edit property, silently ignored obj.foo2 = 'bar2'; // cannot add property, silently ignored With the implementation of ECMA262, JavaScript has the ability to create immutable references that cannot be reassigned. However, using a const declaration doesn't mean that value of the read-only reference is immutable, just that the name cannot be assigned to a new value. const ALWAYS_IMMUTABLE = true; try { ALWAYS_IMMUTABLE = false; } catch (err) { console.log(\"Can't reassign an immutable reference.\"); } const arr = [1, 2, 3]; arr.push(4); console.log(arr); // [1, 2, 3, 4] The use of immutable state has become a rising trend in JavaScript since the introduction of React, which favours Flux-like state management patterns such as Redux. package Immutable; use Moo; has value => ( is => 'ro', # read only default => 'data', # can be overridden by supplying the constructor with # a value: Immutable->new(value => 'something else'); ); 1; Creating an immutable class used to require two steps: first, creating accessors (either automatically or manually) that prevent modification of object attributes, and secondly, preventing direct modification of the instance data of instances of that class (this was usually stored in a hash reference, and could be locked with Hash::Util's lock_hash function): package Immutable; use strict; use warnings; use base qw(Class::Accessor); create read-only accessors __PACKAGE__->mk_ro_accessors(qw(value)); use Hash::Util 'lock_hash'; sub new { my $class = shift; return $class if ref($class); die \"Arguments to new must be key => value pairs\\n\" unless (@_ % 2 == 0); my %defaults = ( value => 'data', ); my $obj = { %defaults, @_, }; bless $obj, $class; # prevent modification of the object data lock_hash %$obj; } 1; Or, with a manually written accessor: package Immutable; use strict; use warnings; use Hash::Util 'lock_hash'; sub new { my $class = shift; return $class if ref($class); die \"Arguments to new must be key => value pairs\\n\" unless (@_ % 2 == 0); my %defaults = ( value => 'data', ); my $obj = { %defaults, @_, }; bless $obj, $class; # prevent modification of the object data lock_hash %$obj; } read-only accessor sub value { my $self = shift; if (my $new_value = shift) { # trying to set a new value die \"This object cannot be modified\\n\"; } else { return $self->{value} } } 1; readonly class BlogData { public string $title; public Status $status; public function __construct(string $title, Status $status) { $this->title = $title; $this->status = $status; } } from typing import Any, NoReturn class ImmutablePoint: \"\"\"An immutable class with two attributes 'x' and 'y'.\"\"\" __slots__: list[str] = [\"x\", \"y\"] def __setattr__(self, *args: tuple[Any, ...]) -> NoReturn: raise TypeError(\"Can not modify immutable instance.\") __delattr__: CallableTuple[Any, ..., NoReturn] = __setattr__ def __init__(self, x: int, y: int) -> None: # We can no longer use self.value = value to store the instance data # so we must explicitly call the superclass super().__setattr__(\"x\", x) super().__setattr__(\"y\", y) The standard library helpers collections.namedtuple and typing.NamedTuple , available from Python 3.6 onward, create simple immutable classes. The following example is roughly equivalent to the above, plus some tuple-like features: from typing import NamedTuple import collections Point: NamedTuple = collections.namedtuple(\"Point\", [\"x\", \"y\"]) the following creates a similar namedtuple to the above class Point(NamedTuple): x: int y: int Introduced in Python 3.7, dataclasses allow developers to emulate immutability with frozen instances. If a frozen dataclass is built, dataclasses will override __setattr__() and __delattr__() to raise FrozenInstanceError if invoked. from dataclasses import dataclass @dataclass(frozen=True) class Point: x: int y: int (struct foo1 (x y)) ; all fields immutable (struct foo2 (x [y #:mutable])) ; one mutable field (struct foo3 (x y) #:mutable) ; all fields mutable The language also supports immutable hash tables, implemented functionally, and immutable dictionaries. // constant items are always immutable const ALWAYS_IMMUTABLE: bool = true; struct MyPair { x: usize, y: usize, } fn main() { // explicitly declare a mutable variable let mut mutable_obj = MyPair { x: 1, y: 2 }; mutable_obj.x = 3; // okay let mutable_ref = &mut mutable_obj; mutable_ref.x = 1; // okay let immutable_ref = &mutable_obj; immutable_ref.x = 3; // error E0594 // by default, variables are immutable let immutable_obj = MyPair { x: 4, y: 5 }; immutable_obj.x = 6; // error E0596 let mutable_ref2 = &mut immutable_obj; // error E0596 let immutable_ref2 = &immutable_obj; immutable_ref2.x = 6; // error E0594 } val maxValue = 100 var currentValue = 1 defines an immutable entity maxValue (the integer type is inferred at compile-time) and a mutable entity named currentValue . By default, collection classes such as List and Map are immutable, so update-methods return a new instance rather than mutating an existing one. While this may sound inefficient, the implementation of these classes and their guarantees of immutability mean that the new instance can re-use existing nodes, which, especially in the case of creating copies, is very efficient. Immutable collections in .NET official library by Microsoft Immutable objects in C# by Tutlane.com",
  "categories": [
    "107076669",
    "108457517",
    "22922580",
    "23117742",
    "23603337",
    "24623845",
    "25257581",
    "26157654",
    "26220375",
    "27395026",
    "27600972",
    "30181011",
    "36975041",
    "43573932",
    "57958211",
    "58191635",
    "58679925",
    "82374028"
  ],
  "license": "CC BY-SA 4.0",
  "source_uri": "https://en.wikipedia.org/w/index.php?oldid=1333190200",
  "content_hash": "",
  "created_at": null,
  "updated_at": 1768542710.0,
  "claims": [],
  "contradictions": [],
  "confidence": 0.6,
  "csl": {
    "id": "enwiki-001333190200",
    "type": "webpage",
    "title": "Immutable object",
    "author": [
      {
        "family": "Anticloud FZ LLE",
        "literal": "Anticloud FZ LLE"
      }
    ],
    "container-title": "encyclopegia.org",
    "publisher": "Anticloud FZ LLE",
    "publisher-place": "Dubai, United Arab Emirates",
    "URL": "https://encyclopegia.org/a/immutable-object",
    "issued": {
      "date-parts": [
        [
          2026,
          11,
          19
        ]
      ]
    },
    "accessed": {
      "date-parts": [
        [
          2026,
          11,
          19
        ]
      ]
    },
    "license": "CC BY-SA 4.0",
    "DOI": "eo1:enwiki-001333190200",
    "isBasedOn": "https://en.wikipedia.org/w/index.php?oldid=1333190200",
    "note": "Immutable snapshot enwiki-001333190200"
  }
}