Why are data types either mutable or immutable?
Lets look at python as an example,
Data types in python are basically objects or classes, int is a class, floats, lists etc.
Therefore, writing x=6 creates a new integer object with a value of 6 and points a reference called x at this object.
Now we need to look into classes, classes basically group data and functions together, there functions are called Methods and they are of two types: accessor and mutator methods.
Accessor methods access the current state of an object but doesn't change the object itself e.g
x = "hello"
y = x.upper()
Here the method upper is called on the object that x refers to, the upper accessor then returns a new object, a str object that is an upper-cased version of the original string. (feel free to re-read) , basically it returns a new object based on the original now only it is uppercased.
Mutator methods on the other hand change the values in the existing objects and a good example is the list type(class).
newList = [1,2,3]
newList.reverse()
This method will mutate the existing object, a mutator method can't be undone.
Data types that lack these mutator methods are said to be immutable and hence only contain accessor methods, one that lack are mutable.
Hope this helped, stay curious :)
The above is the detailed content of What do we REALLY mean by immutable data types?. For more information, please follow other related articles on the PHP Chinese website!