Questions tagged [immutability]

Immutability is the inability to modify data after it has been created. Modifications are instead made by copying the data. A property of immutable data is that it is *referentially transparent*.

immutability
Filter by
Sorted by
Tagged with
715 votes
27 answers
1.8m views

Remove specific characters from a string in Python

I'm trying to remove specific characters from a string using Python. This is the code I'm using right now. Unfortunately, it appears to do nothing to the string. for char in line: if char in "...
Matt Phillips's user avatar
663 votes
13 answers
193k views

Why are exclamation marks used in Ruby methods?

In Ruby some methods have a question mark (?) that ask a question like include? that ask if the object in question is included, this then returns a true/false. But why do some methods have ...
Lennie's user avatar
  • 10.7k
555 votes
16 answers
107k views

Why are mutable structs “evil”?

Following the discussions here on SO I already read several times the remark that mutable structs are “evil” (like in the answer to this question). What's the actual problem with mutability and ...
Dirk Vollmar's user avatar
422 votes
17 answers
192k views

What is meant by immutable?

What exactly does immutable mean - that is, what are the consequences of an object being mutable or immutable? In particular, why are Java's Strings immutable? My understanding is that the ...
ashokgelal's user avatar
  • 80.6k
417 votes
16 answers
59k views

Is a Java string really immutable?

We all know that String is immutable in Java, but check the following code: String s1 = "Hello World"; String s2 = "Hello World"; String s3 = s1.substring(6); System.out.println(s1); // Hello ...
Darshan Patel's user avatar
389 votes
18 answers
241k views

Const in JavaScript: when to use it and is it necessary?

I've recently come across the const keyword in JavaScript. From what I can tell, it is used to create immutable variables, and I've tested to ensure that it cannot be redefined (in Node.js): const x = ...
axdg's user avatar
  • 4,035
295 votes
13 answers
146k views

What is the difference between shallow copy, deepcopy and normal assignment operation?

import copy a = "deepak" b = 1, 2, 3, 4 c = [1, 2, 3, 4] d = {1: 10, 2: 20, 3: 30} a1 = copy.copy(a) b1 = copy.copy(b) c1 = copy.copy(c) d1 = copy.copy(d) print("immutable - id(a)==id(a1)", id(a) ==...
deeshank's user avatar
  • 4,426
290 votes
16 answers
669k views

Correct way to push into state array

I seem to be having issues pushing data into a state array. I am trying to achieve it this way: this.setState({ myArray: this.state.myArray.push('new value') }) But I believe this is incorrect way ...
Ilja's user avatar
  • 45.2k
276 votes
14 answers
71k views

Why is immutability so important (or needed) in JavaScript?

I am currently working on React JS and React Native frameworks. On the half way road I came across Immutability or the Immutable-JS library, when I was reading about Facebook's Flux and Redux ...
bozzmob's user avatar
  • 12.4k
255 votes
27 answers
140k views

How to make an immutable object in Python?

Although I have never needed this, it just struck me that making an immutable object in Python could be slightly tricky. You can't just override __setattr__, because then you can't even set attributes ...
Lennart Regebro's user avatar
238 votes
26 answers
107k views

Immutability of Strings in Java

Consider the following example. String str = new String(); str = "Hello"; System.out.println(str); //Prints Hello str = "Help!"; System.out.println(str); //Prints Help! Now, ...
Light_handle's user avatar
  • 3,977
233 votes
76 answers
17k views

What's the best name for a non-mutating "add" method on an immutable collection? [closed]

Sorry for the waffly title - if I could come up with a concise title, I wouldn't have to ask the question. Suppose I have an immutable list type. It has an operation Foo(x) which returns a new ...
229 votes
19 answers
315k views

String is immutable. What exactly is the meaning? [duplicate]

I wrote the following code on immutable Strings. public class ImmutableStrings { public static void main(String[] args) { testmethod(); } private static void testmethod() { ...
Anuj Balan's user avatar
  • 7,669
229 votes
14 answers
146k views

What would a "frozen dict" be?

A frozen set is a frozenset. A frozen list could be a tuple. What would a frozen dict be? An immutable, hashable dict. I guess it could be something like collections.namedtuple, but that is ...
dugres's user avatar
  • 12.9k
221 votes
19 answers
192k views

Enums in Javascript with ES6

I'm rebuilding an old Java project in Javascript, and realized that there's no good way to do enums in JS. The best I can come up with is: const Colors = { RED: Symbol("red"), BLUE: Symbol("...
cypherfunc's user avatar
  • 2,391
215 votes
11 answers
96k views

Immutable vs Unmodifiable collection [duplicate]

From the Collections Framework Overview: Collections that do not support modification operations (such as add, remove and clear) are referred to as unmodifiable. Collections that are not ...
Cratylus's user avatar
  • 53.5k
213 votes
8 answers
44k views

Why can tuples contain mutable items?

If a tuple is immutable then why can it contain mutable items? It is seemingly a contradiction that when a mutable item such as a list does get modified, the tuple it belongs to maintains being ...
qazwsx's user avatar
  • 26.2k
209 votes
20 answers
288k views

Immutable vs Mutable types

I'm confused on what an immutable type is. I know the float object is considered to be immutable, with this type of example from my book: class RoundFloat(float): def __new__(cls, val): ...
user1027217's user avatar
  • 2,261
202 votes
13 answers
115k views

Why .NET String is immutable? [duplicate]

As we all know, String is immutable. What are the reasons for String being immutable and the introduction of StringBuilder class as mutable?
Nirajan Singh's user avatar
202 votes
12 answers
106k views

Mutable vs immutable objects

I'm trying to get my head around mutable vs immutable objects. Using mutable objects gets a lot of bad press (e.g. returning an array of strings from a method) but I'm having trouble understanding ...
Alex Angas's user avatar
  • 59.7k
198 votes
17 answers
122k views

Remove a property in an object immutably

I am using Redux. In my reducer I'm trying to remove a property from an object like this: const state = { a: '1', b: '2', c: { x: '42', y: '43' }, } And I want to have ...
Vincent Taing's user avatar
189 votes
8 answers
130k views

Error: "Cannot modify the return value" c#

I'm using auto-implemented properties. I guess the fastest way to fix following is to declare my own backing variable? public Point Origin { get; set; } Origin.X = 10; // fails with CS1612 Error ...
P a u l's user avatar
  • 7,835
176 votes
7 answers
82k views

Swift make method parameter mutable?

How can I deal with this error without creating additional variable? func reduceToZero(x:Int) -> Int { while (x != 0) { x = x-1 // ERROR: cannot assign to 'let' value 'x' ...
Gabriel's user avatar
  • 1,897
176 votes
15 answers
133k views

Immutable array in Java

Is there an immutable alternative to the primitive arrays in Java? Making a primitive array final doesn't actually prevent one from doing something like final int[] array = new int[] {0, 1, 2, 3}; ...
user avatar
174 votes
13 answers
41k views

How to avoid "too many parameters" problem in API design?

I have this API function: public ResultEnum DoSomeAction(string a, string b, DateTime c, OtherEnum d, string e, string f, out Guid code) I don't like it. Because parameter order becomes ...
156 votes
10 answers
68k views

Advantages of stateless programming?

I've recently been learning about functional programming (specifically Haskell, but I've gone through tutorials on Lisp and Erlang as well). While I found the concepts very enlightening, I still don't ...
Sasha Chedygov's user avatar
145 votes
7 answers
27k views

What is the difference between immutable and const variables in Rust?

I learned that if a variable is not explicitly declared mutable using mut, it becomes immutable (it cannot be changed after declaration). Then why do we have the const keyword in Rust? Aren't they the ...
7_R3X's user avatar
  • 4,152
140 votes
10 answers
120k views

Remove value from object without mutation

What's a good and short way to remove a value from an object at a specific key without mutating the original object? I'd like to do something like: let o = {firstname: 'Jane', lastname: 'Doe'}; let ...
amann's user avatar
  • 5,714
140 votes
12 answers
34k views

Why does C# disallow readonly local variables? [closed]

Having a friendly debate with a co-worker about this. We have some thoughts about this, but wondering what the SO crowd thinks about this?
Brian Genisio's user avatar
137 votes
22 answers
162k views

Aren't Python strings immutable? Then why does a + " " + b work?

My understanding was that Python strings are immutable. I tried the following code: a = "Dog" b = "eats" c = "treats" print a, b, c # Dog eats treats print a + " " + b + " " + c # Dog eats treats ...
jason's user avatar
  • 5,431
136 votes
3 answers
55k views

How do I work around mutability in moment.js?

I've run into a problem where I have to store the initial values of a moment object but I'm having some trouble preventing my variable from changing along with the original object. Unfortunately ...
Shengbo1618's user avatar
  • 1,463
132 votes
9 answers
111k views

Does Python have an immutable list?

Does python have immutable lists? Suppose I wish to have the functionality of an ordered collection of elements, but which I want to guarantee will not change, how can this be implemented? Lists are ...
cammil's user avatar
  • 9,745
129 votes
7 answers
210k views

Java Immutable Collections

From Java 1.6 Collection Framework documentation: Collections that do not support any modification operations (such as add, remove and clear) are referred to as unmodifiable. [...] Collections that ...
Bhaskar's user avatar
  • 7,473
127 votes
8 answers
63k views

How do I create an immutable Class?

I am working on creating an immutable class. I have marked all the properties as read-only. I have a list of items in the class. Although if the property is read-only the list can be modified. ...
Biswanath's user avatar
  • 9,115
119 votes
10 answers
163k views

Replace Multiple String Elements in C#

Is there a better way of doing this... MyString.Trim().Replace("&", "and").Replace(",", "").Replace(" ", " ") .Replace(" ", "-").Replace("'", "").Replace("/", "").ToLower(); I've ...
Chris McKee's user avatar
  • 4,347
114 votes
12 answers
84k views

Is Integer Immutable

I know this is probably very stupid, but a lot of places claim that the Integer class in Java is immutable, yet the following code: Integer a=3; Integer b=3; a+=b; System.out.println(a); Executes ...
K.Steff's user avatar
  • 2,174
111 votes
10 answers
41k views

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 ...
alex's user avatar
  • 485k
111 votes
5 answers
17k views

val-mutable versus var-immutable in Scala

Are there any guidelines in Scala on when to use val with a mutable collection versus using var with an immutable collection? Or should you really aim for val with an immutable collection? The fact ...
James McCabe's user avatar
  • 1,869
102 votes
4 answers
7k views

If Python strings are immutable, why does it keep the same id if I use += to append to it?

Strings in Python are immutable, which means the value cannot be changed. However, when appending to the string in the following example, it looks like the original string memory is modified since the ...
Master_Roshy's user avatar
  • 1,245
100 votes
9 answers
36k views

Hashable, immutable [duplicate]

From a recent SO question (see Create a dictionary in python which is indexed by lists) I realized I probably had a wrong conception of the meaning of hashable and immutable objects in python. What ...
joaquin's user avatar
  • 84.3k
99 votes
3 answers
47k views

Immutable numpy array?

Is there a simple way to create an immutable NumPy array? If one has to derive a class from ndarray to do this, what's the minimum set of methods that one has to override to achieve immutability?
NPE's user avatar
  • 493k
97 votes
11 answers
40k views

Why would one declare an immutable class final in Java?

I read that to make a class immutable in Java, we should do the following, Do not provide any setters Mark all fields as private Make the class final Why is step 3 required? Why should I mark ...
Anand's user avatar
  • 21k
97 votes
2 answers
14k views

Isn't Redux just glorified global state?

So I started learning React a week ago and I inevitably got to the problem of state and how components are supposed to communicate with the rest of the app. I searched around and Redux seems to be the ...
Ryan Peschel's user avatar
  • 11.5k
96 votes
9 answers
13k views

Building big, immutable objects without using constructors having long parameter lists

I have some big (more than 3 fields) objects that can and should be immutable. Every time I run into that case I tend to create constructor abominations with long parameter lists. It doesn't feel ...
Malax's user avatar
  • 9,516
95 votes
20 answers
69k views

Why do we need immutable class?

I am unable to get what are the scenarios where we need an immutable class. Have you ever faced any such requirement? or can you please give us any real example where we should use this pattern.
Rakesh Juyal's user avatar
  • 36.2k
93 votes
12 answers
107k views

In Python, how can I make unassignable attributes (like ones marked with `final` in Java)?

Is there anything in Python that works like the final keyword in Java - i.e., to disallow assigning to a specific attribute of the instances of a class, after those instances have been created? I ...
Jason Coon's user avatar
93 votes
14 answers
63k views

Immutable class?

How can one make a Java class immutable, what is the need of immutability and is there any advantage to using this?
JavaUser's user avatar
  • 25.9k
92 votes
7 answers
93k views

Immutable/Mutable Collections in Swift

I was referring to Apple's Swift programming guide for understanding creation of Mutable/ immutable objects(Array, Dictionary, Sets, Data) in Swift language. But I could't understand how to create a ...
Pranav Jaiswal's user avatar
87 votes
8 answers
51k views

In C#, why can't I modify the member of a value type instance in a foreach loop?

I know that value types should be immutable, but that's just a suggestion, not a rule, right? So why can't I do something like this: struct MyStruct { public string Name { get; set; } } public ...
Cui Pengfei 崔鹏飞's user avatar
86 votes
9 answers
39k views

How can I create a new instance of ImmutableDictionary?

I would like to write something like this: var d = new ImmutableDictionary<string, int> { { "a", 1 }, { "b", 2 } }; (using ImmutableDictionary from System.Collections.Immutable). It seems like ...
Lukáš Lánský's user avatar

1
2 3 4 5
75