[2] Other benefits are that they are simpler to understand and reason about and offer higher security than mutable objects.
Examples include conversion factors from meters to feet, or the value of pi to several decimal places.
Read-only fields may be calculated when the program runs (unlike constants, which are known beforehand), but never change after they are initialized.
Some languages reverse it: in OCaml, fields of an object or record are by default immutable, and must be explicitly marked with mutable to be so.
This is done to conserve memory by preventing data duplication and avoid calls to constructors and destructors; it also results in a potential boost in execution speed.
In these situations, defensive copying of the entire object rather than the reference is usually an easy but costly solution.
A technique that blends the advantages of mutable and immutable objects, and is supported directly in almost all modern hardware, is copy-on-write (COW).
(Even if the algorithm is not guaranteed to be comprehensive, there still exists the possibility of a fast path case improvement when the objects are equal and use the same reference.)
Rather, immutability is a compile-time construct that indicates what a programmer can do through the normal interface of the object, not necessarily what they can absolutely do (for instance, by circumventing the type system or violating const correctness in C or C++).
[8][9] In C++, a const-correct implementation of Cart would allow the user to create instances of the class and then use them as either const (immutable) or mutable, as desired, by providing two different versions of the items() 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.
[10] Unlike C++'s const, Java's final, and C#'s readonly, they are transitive and recursively apply to anything reachable through references of such a variable.
In a function like this: Inside the braces, c might refer to the same object as m, so mutations to m could indirectly change c as well.
Values that are const or immutable must be initialized by direct assignment at the point of declaration or by a constructor.
"[10] 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.
[11] 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.
A classic example of an immutable object is an instance of the Java String class The method toLowerCase() does not change the data "ABC" that s contains.
Primitive wrappers (Integer, Long, Short, Double, Float, Character, Byte, Boolean) are also all immutable.
[13] In JavaScript, all primitive types (Undefined, Null, Boolean, Number, BigInt, String, Symbol) are immutable, but custom objects are generally mutable.
[14] In Perl, one can create an immutable class with the Moo library by simply declaring all the attributes read only: 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): Or, with a manually written accessor: In PHP have readonly properties since version 8.1 and readonly classes since version 8.2.
[15][16] In Python, some built-in types (numbers, Booleans, strings, tuples, frozensets) are immutable, but custom classes are generally mutable.
The following example is roughly equivalent to the above, plus some tuple-like features: Introduced in Python 3.7, dataclasses allow developers to emulate immutability with frozen instances.
Racket substantially diverges from other Scheme implementations by making its core pair type ("cons cells") immutable.
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.