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*.

0
votes
1answer
36 views

Is there a safe way to reuse the same code for immutable and mutable variants of a function? [duplicate]

I did a bit of searching, and found this Reddit post from four years ago, but other than unsafe code: fn find_mut <'a> (&'a mut self, elem: &T) -> Option<&'a mut Node<T>&...
1
vote
0answers
20 views

variable reference and mutability

I've found many articles providing examples like the following: listA = [0] listB = listA listB.append(1) print listA print listB The gaol is to show that both lists are pointing to the same object, ...
0
votes
1answer
20 views

Set an object with Immutability-Helper

I'm trying to update State with Immutability-Helper and React but I don't have result expected. constructor(props) { super(props); this.state = { parents: {} }; } handleParent = ...
0
votes
2answers
11 views

How to add elements to CopyInWriteCollection using Kotlin style?

Assume we have a custom collection class CopyOnWriteCollection<T> { // returns copy of collection with new element fun add(element: T): CopyOnWriteCollection<T> { ... } } ...
0
votes
1answer
22 views

python strings are immutable yet “re.sub()” can mutate it how?

Here, string flight_details string is changed but its id does not change, below is the code and its output: import re flight_details = "Flight Savana Airlines a2134" print(id(flight_details)) print(...
0
votes
3answers
33 views

I want to use spread operator to add data to my array

I want to use spread operator to add data to my array. This works when its an object { ...state, selections: { ...state.selections, [action.data.type]: action.data } But when its an ...
-1
votes
0answers
29 views

Need help for understanding object / Array Immutability in vue.js [duplicate]

I am trying to update an object of a specific array index, using spread operator on a const object in vuex store and pushing the new object into the array somehow get mutated. What I am doing wrong? ...
2
votes
1answer
67 views

How to freeze an array in swift?

In js I can freeze an array after adding some elements to an array. Is there anything to freeze an array in Swift? What is freezing? Ans: Suppose we have an array. We add some elements to ...
0
votes
1answer
21 views

Conditional increment in xsl for-each loop

Given the following XML format: <?xml version="1.0"?> <items> <id>7</id> <id></id> <id/> <id>9</id> <id/> </items> I'd ...
0
votes
2answers
36 views

How to assign variable in pattern matching

I have a method that takes a year (int) as a parameter. Depending on the passed in year, I need to assign a variable and then use that variable in a query: def findByYear (year: Int): Future[Int] = { ...
2
votes
3answers
52 views

What are the drawbacks in returning empty immutable collection instead of allocating a new and empty one?

I used to call for Collections.emptyList(), emptySet and emptyMap to return a reference to an immutable empty collection instead of null from my functions. That's because I see no reasons to allocate ...
0
votes
3answers
68 views

Is there a recommended way of ensuring immutability

I am observing following behavior since python passes object by reference? class Person(object): pass person = Person() person.name = 'UI' def test(person): person.name = 'Test' test(...
3
votes
1answer
53 views

Case class immutable still able to change the parameter values

I reviewed some code from a colleague and I came across a case class which is by default immutable. the below case class can be changed so my question is how is this possible since case classes are ...
2
votes
1answer
78 views

Cannot access properties of an object, but the object exists [duplicate]

I was trying to sort an array of user objects coming back from the database base on their age, but something really strange happened. The following code isn't working: async function getAllUsers(){ ...
1
vote
1answer
49 views

How to create a class as immutable in java which is having many fields?

I have got an interview question where interviewer asked me, "How will you create an immutable class in java, which class will have more than 100 fields in it?" As we know to create immutable class ...
1
vote
0answers
38 views

Python mutable and immutable [duplicate]

I encountered to this example about python mutable and immutable: t = (1, 2, [3, 4]) t[2] += [5, 6] This will raise error: TypeError: 'tuple' object does not support item assignment Until here I ...
0
votes
3answers
21 views

Immutable remove object entry react reducer

I want to immutable remove an object entry in react reducer obj = { selections: {} } this is how i add things to my selections obj return { ...state, selections: { ...state.selections, ...
-2
votes
5answers
86 views

Why can't an immutable class have setter methods? [duplicate]

I was reading about immutable classes, and the ways to make a class immutable were said to be: 1 - Make the class final to prevent inheritance 2 - Make the mutable variables final 3 - Don't ...
0
votes
0answers
29 views

C# ImmutableObject attribute doesn't work, still can change struct value [duplicate]

It's said, a best practice is to make structs immutable, so I did this: struct MyStruct { public int mI; public string mS; } [ImmutableObject(true)] struct ComplexStruct { public int mJ; ...
1
vote
2answers
58 views

modification for Immutable array not working [duplicate]

Modified the code for making the array immutable, but its getting wrong somewhere.As in the code, when object created for ImmutableClassWithArray, the list is being initialised with given array. ...
1
vote
0answers
48 views

How can one struct own both a sequence and an iterator on the sequence? [duplicate]

I am trying to construct a Defiler struct that owns a fixed sequence and an internal state describing current position within this sequence. The idea is that it can be iterated upon, but sometimes be ...
0
votes
0answers
40 views

What are all the number of ways the immutability of a class can be broken? [duplicate]

Suppose I have a class which I have made immutable by following the steps below only. Mark class as final which has two fields one is String and other is List type. mark fields as private but NOT ...
0
votes
1answer
40 views

How to let variable become immutable after one change?

first value from event data: A = 100; start_value = A; start_value = 100 but A is constantly changing due to JSON.parse(evt.data) from sensors so after a while if: A = 500 start_value = 500 How ...
-1
votes
0answers
24 views

Set key value in immutable map cause entries inside Immutable Map

I am looping through key value items and I need to add it to a Map with set() like below (stateName is a string and result is a map): promises.then(promise => promise.map(([stateName, item]) => ...
-1
votes
0answers
60 views

Are C# Strings still Immutable? [duplicate]

I am learning C# and was taught that strings are immutable, meaning once they are assigned a value, that value cannot be changed; however, this does not appear to be the case. See code below: using ...
0
votes
2answers
62 views

What is the Pythonic way to make an immutable class?

I'm currently working with some data structures in Python, and I would like them to be hashable (so they can be stored in dictionaries and sets). So far I've seen three main ways to do this: ① Make a ...
3
votes
3answers
59 views

Is it possible to force data immutability in a python function?

Say I define a list object and only want it to be read-only in a function I define. In C++, you'd do this with a const reference. Is there any way to do this with a python function? Does this make ...
1
vote
0answers
39 views

Does immutability allow values to be changed or not?

There is a hole in my understanding of immutability. I frequently hear that: immutability means a value doesn't change ...but how does a programmer handle when whatever they are modelling does ...
0
votes
1answer
37 views

How to serialize immutable struct

I am trying to serialize an immutable struct using JSon.NETand i do not how to do it .The result of the serialization is an empty json {}.I would prefer to use JsonNET and not something heavy like the ...
3
votes
1answer
53 views

Why isn't “is” comparison used in place of “==” for primitive types?

When I'm using Pytest for Python formatting, it complains about doing something like: >>> assert some_function_ret_val() == True E712 comparison to True should be 'if cond is True:' or 'if ...
0
votes
1answer
70 views

Updating mutable HashMap in a while loop

I am trying to implement Karger's algorithm in Rust and I have run into an issue while trying to update a mutable hashmap in a while loop. The map is updated successfully, but then in the next ...
1
vote
0answers
32 views

How do I deserialize my immutable subclass?

I'm currently trying to deserialize a json-response. My object uses the builder pattern and the consumer interface. I'm doing a http-request to an external source and get my response as json. All the ...
2
votes
1answer
31 views

How to initialize final member with other final member in StatelessWidget subclass?

I have a simple StatelessWidget that creates a new StatefulWidget in its constructor. The problem is that to create that widget, another object needs to be created first. And then when I pass it to ...
1
vote
1answer
35 views

Remove last element of array in Redux with immutability-helper without knowing array's length

I am using immutability-helper (https://github.com/kolodny/immutability-helper) to update state in Redux actions. I have an array and I'm adding an element like this: update(state, { modalAlerts: { $...
0
votes
0answers
19 views

How can I set the unique id inside the object in database?

I started working at a new app (react typescript) and I am using firebase. I'm pretty new to it and I am curious about 2 things. If I use axios.post to post an object like this { field1: "data1", ...
-1
votes
3answers
42 views

What the difference between hash-able and immutable? [closed]

What's the difference between immutable and hash-able ? What does this mean "An object is hashable if it has a hash value which never changes during its lifetime?" Is a tuple immutable and hashable ...
0
votes
0answers
39 views

Unexpected behavior due to possible variable aliasing

C++ programmer here doing Python. The input U to the method do_something() changes from [1.0] to [0.0] upon calling the method clear(). Debugging made it clear that the line self.current *= 0 is the ...
2
votes
3answers
83 views

Variable assignment and modification with regards to memory addresses

Suppose I assign two variables to integers: a = 1 b = 2 Now, I'll assign a to b: a = b As expected, a == 2, because a has been set to the memory address of b. But actually, it hasn't. If I do b ...
-3
votes
3answers
55 views

Is it legitimate to define final an immutable parameter, bind the parameter to another local variable and mutate the local variable?

Note well: The same question applies for other immutable types, like String and Boolean. I have a method like this (this is a simple example of a more complicated method): Example 1 public ...
0
votes
0answers
8 views

Vuex and the mutate thing, the immutability and the clone deep hell

This is not a questions itself, but a good issue to Vue community. I want to open a discussion about Vuex and immutability. When we enable Vuex strict mode and when we have within the state an object ...
5
votes
1answer
82 views

Mutable and Immutable in Python

I am new to Python and trying to understand the difference between mutable and immutable objects. One of the mutable types in Python is list. Let's say L = [1,2,3], then L has a id that points the ...
0
votes
0answers
29 views

Why should the state in React components be immutable [duplicate]

I am sorry if this has been asked before, but I googled around and could not find the real explanation why the state should be immutable. I found for most cases mutating the state still makes the ...
2
votes
1answer
130 views

How to interpret immutable references to mutable types in Rust?

It seems that I cannot mutate anything if there is any immutable reference in my chain of dereferencing. A sample: fn main() { let mut x = 42; let y: &mut i32 = &mut x; // first layer ...
1
vote
0answers
85 views

How to use ImmutableArray (C#) in MongoDB?

I am trying to save ImmutableArray (System.Collections.Immutable) in MongoDB. I tried MongoDB.Immutable but it is limited to old version of Immutable package, and doesn't support ImmutableArray. I ...
-4
votes
1answer
21 views

Keep frozen object as global state [closed]

I am playing around with immer.js and i came up with question is it ok to assigned and keep frozen object to global state after like let initialState = {a: 'a'}; const nextState = produce(...
0
votes
1answer
45 views

A better way of transforming a nested clojure data structure

I have a clojure map that looks like this: {"l1" [{"name" "s1", "url" "something", "coordinates" {"latitude" 100, "longitude" 200}} {"name" "s2", "url" "something", "coordinates" {"latitude" ...
4
votes
4answers
82 views

How to make a class immutable when its referencing a mutable object?

Let's say I have a class in java called Employee that looks something like this public class Employee { private String empName; private int empId; public String getEmpName() { ...
0
votes
2answers
26 views

Mutable Wrapper for Immutable Dictionary

Here is the problem; I have an immutable dictionary with huge set of items. The key type and the value types contained within this dict are themselves immutable. I would like to be able to mutate this ...
0
votes
1answer
30 views

Immutable Objects in R - what happens here under the hood?

I am a little bit confused. I learned to never grow a vector because we do not want to create a new copy of an object every time. # Bad start <- Sys.time() vector1 <- vector() for(i in 1:...
8
votes
2answers
123 views

Creating a hash that is read-only outside of a module, but read/write inside

I am creating a module that has some fairly heavily nested hashes. The hash needs to be semi-regularly modified by the module, which unfortunately rules out using Map. Generally, a branch of the ...