Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does immutable mean?

If a string is immutable, does that mean that.... (let's assume JavaScript)

var str = 'foo';  alert(str.substr(1)); // oo  alert(str); // foo 

Does it mean, when calling methods on a string, it will return the modified string, but it won't change the initial string?

If the string was mutable, does that mean the 2nd alert() would return oo as well?

like image 823
alex Avatar asked Jul 08 '10 01:07

alex


People also ask

What is an example of immutable?

String is an example of an immutable type. A String object always represents the same string.

What does mean immutable in programming?

In object-oriented 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.

What does immutable mean in the Bible?

The Immutability of God is an attribute that "God is unchanging in his character, will, and covenant promises." The Westminster Shorter Catechism says that "[God] is a spirit, whose being, wisdom, power, holiness, justice, goodness, and truth are infinite, eternal, and unchangeable." Those things do not change.

What is meant by immutable in Python?

Immutable is the when no change is possible over time. In Python, if the value of an object cannot be changed over time, then it is known as immutable. Once created, the value of these objects is permanent.


1 Answers

It means that once you instantiate the object, you can't change its properties. In your first alert you aren't changing foo. You're creating a new string. This is why in your second alert it will show "foo" instead of oo.

Does it mean, when calling methods on a string, it will return the modified string, but it won't change the initial string?

Yes. Nothing can change the string once it is created. Now this doesn't mean that you can't assign a new string object to the str variable. You just can't change the current object that str references.

If the string was mutable, does that mean the 2nd alert() would return oo as well?

Technically, no, because the substring method returns a new string. Making an object mutable, wouldn't change the method. Making it mutable means that technically, you could make it so that substring would change the original string instead of creating a new one.

like image 171
kemiller2002 Avatar answered Oct 04 '22 15:10

kemiller2002