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*.
3,675
questions
0
votes
2
answers
82
views
How to protect class instance against alteration
How can I modify the body of the code (this can include the body of the constructor) to protect Person instances against alteration: Once a Person is created, it should not be possible to modify it.
...
0
votes
1
answer
64
views
Protect individual values in std::array while allowing complete overwrite
I have an array which is global state. This is running in an embedded/microcontroller environment, not a large application where I might be more concerned about global state.
How can I declare the ...
-1
votes
1
answer
60
views
C# object's returning internal components
Goal
A very recurrent design I would like to implement in C# is following: A class, that owns multiple instances of another class.
For clarity let's pick an example, let's say a "car" that ...
0
votes
0
answers
31
views
Why does rust allow us to store mutablre referneces to a immutable variable? [duplicate]
In rust, if we can store mutable reference to a mutable variable, like so:
fn main() {
let mut str: String = String::new(); // a mutable string
let ref1 = &mut str; // storing a mutable ...
-1
votes
0
answers
79
views
Return an immutable vector of unique_ptr
I have the following object:
class Container {
public:
std::vector<std::unique_ptr<Item>>& items() { return m_items; }
private:
std::vector<std::unique_ptr<Item>> ...
0
votes
0
answers
16
views
React - Child components not updating when setting the parent's state too quickly
I have a big form with around 1000 dynamically rendered inputs (based on a database table) and each have their own reference in the parent's state array inputs. Here is the structure of said array :
[
...
0
votes
1
answer
28
views
In React functional components, if I just make a new copy of array but keep the objects, does it break the pattern?
Let's say if my app or component has an array of personInfo.
const [persons, setPersons] = useState([{ name: "", phone: ""}]);
so that I can add a person, remove a person, edit ...
1
vote
3
answers
44
views
Make polyfills immutable
For example:
Object.defineProperty(Promise.prototype, 'onFinally', {
get: () => {},
writable: false,
});
or
Object.freeze(Promise.prototype);
These examples aren't work, is there a working ...
1
vote
1
answer
47
views
Deep Copy of Cons instance of Java List interface
I am implementing a immutable List interface in java, a Cons class, essentially a list of lists ie; Cons(1,2,3)= Cons(1,Cons(2,Cons(3,null)))
I am trying to create a deepcopy of a cons but have had no ...
4
votes
1
answer
34
views
How can non-built-in type instances be immutable in python?
If I try to run
import numpy as np
type(np.dtype).moo = 7
then I get
TypeError: cannot set 'moo' attribute of immutable type 'numpy._DTypeMeta'
which I can't find an explanation for.
numpy....
-3
votes
1
answer
62
views
Naming convention for a method that create a new object from the current instance but modifies some properties [closed]
I was wondering if there are any common conventions for a method that:
returns a new instance of the same type of object;
using the current instance's property values as the defaults;
while changing ...
0
votes
0
answers
16
views
What is an immutable string? [duplicate]
I’m very new to coding and want to know what an immutable string is. I’ve read that this means that a string object can’t be changed once it’s created.
String = ‘hello’
String = ‘bye’
Would the second ...
0
votes
1
answer
32
views
Usage of Equatable in Flutter Dart
Im currently working on a Flutter school project.
Im totaly new to Flutter and Dart and have troubles to understand the usage of Equatable package.
I build my Flutter Application using the Bloc-...
0
votes
0
answers
27
views
Handling frequent updates in data layer, isn't immutabability a performance problem?
Lets say I have a list of many items, displaying on the screen, e.g.
list with three sliders, showing the value
In my understanding, a typical architectural pattern with Jetpack Compose contains ...
1
vote
2
answers
66
views
Lombok Value annotation not working properly for Immutable java class
I was looking to see if it's possible to create an immutable Java class using Lombok. I found this page on the Lombok website "Immutable classes made very easy", but I'm not convinced by it: ...
1
vote
2
answers
45
views
Why after calling "defineProperties", my object became empty
I have this object
const product = {
name: "Laptop",
price: 1000,
quantity: 5
};
console.log(product) //{ name: 'Laptop', price: 1000, quantity: 5 }
but then I should to ...
-1
votes
3
answers
56
views
Python mutable/immutable and local variables
I am quite confused about a difference in behavior of the two following code snippets, and in particular about expectations of their behavior in the mutability/immutability in Python concept:
Snippet ...
2
votes
1
answer
62
views
Shallow Copying Class Objects vs. String Variables
string a = "John";
string b = "Doe";
a = b; // Shallow copying strings
b = "Elon Musk";
Console.WriteLine(a); // Output: Doe
This prints "Doe", meaning the ...
1
vote
0
answers
37
views
Unable to render images to a PPTX slideshow using Apache POI
I have this code that reads a .pptx template file to fetch placeholder mappings and then subsequently replace these placeholders with actual data. It uses Apache POI in Scala.
Here is my code:
def ...
-1
votes
2
answers
49
views
Can I annotate a member field as read only or immutable in Python? [duplicate]
I am not looking for a "physically" immutable member field in Python as I know it is
impossible, but just a type annotation to tell type checker that this field should not be re-assign a new ...
0
votes
0
answers
16
views
Why a String which by definition is immutable can change its size?
I know that String is immutable which means once created it cannot change its size (can't become larger or smaller) or it cant be changed any of its characters. Now, I found 2 examples and it is a bit ...
0
votes
0
answers
42
views
Why is my array only storing one item and replacing the old item with the new one?
I have a checklist component on a React form. When an item is checked, I want to immutably add it to checkboxVal state array, when unchecked, I want to remove it. Currently, when I check a new value, ...
0
votes
2
answers
66
views
Scala val and var with collections
I want to understand better the following issue.
When should i use var and when val?
I know that there is a rule of thumb in Scala that we should use val.
For primitive types it's easy - we should use ...
1
vote
1
answer
53
views
I can write an immutable variable in rust
let mut a = Box::new("123".to_string());
let b = Box::new( &mut a);
b.push('4');
assert_eq!( "1234", b.as_str());
// lets see the types:
// let x001: Box<&...
0
votes
0
answers
60
views
How are python lists and tuples stored in memory?
Python lists are mutable because they store references to their elements, instead of the elements themselves. Which means, the list variable would have a different address than the address of its ...
1
vote
1
answer
64
views
Depth first search: is immutabilty and speed mutualy exclusive?
The DFS I was taught in school goes something like this:
(* graph representation: ith element of the array is a list of successors of the node i *)
let graph_example = [|
[1; 2];
[3; 0; 2];
[0; ...
2
votes
1
answer
69
views
Can I declare a constructor that accepts Name-Value arguments to define immutable properties?
Since MATLAB R2019b it has been possible to declare name-value arguments from class properties which has created an elegant way to define a class that can be constructed with a declaration of its ...
0
votes
0
answers
80
views
Persistent data structures in Rust
How to implementing a basic persistent data structure that utilizes structural sharing? The code provided below is functional, but I would like to receive input on whether this approach is suitable ...
0
votes
1
answer
81
views
Mutability in Rust: value borrowed after move?
I've been writing a small process manager that monitors the state of a few spawned processes and aims to keep them up whenever they get killed. Unfortunately, I seem to be facing mutability issues ...
-1
votes
1
answer
40
views
Double linked immutable objects (C# records)
I want to create two-way linked objects (parent with child, where Parent.Child property refers to the parent's child, and Child.Parent refers to the child's parent).
From what I see, this would only ...
2
votes
2
answers
58
views
Array passed as prop doesn't reflect changes
This question is more for understanding more how react handles and reacts to changes, than implementation, therefore I'm letting immutable-props-apprach go for a little bit.
I'm trying to get the ...
0
votes
0
answers
42
views
Spread operator vs filter in React/immutable data?
Possibly related to Array.from() vs spread syntax
This is just a theoretical question, in reality we wouldn't have a such huge json dumped into the client side.
Let's say we have a object such that
{
...
0
votes
2
answers
226
views
How to use late final keyword in Flutter Dart freezed model?
How to use late final keyword in Flutter Dart freezed model ?
This code generates successfully and has no static analysis error but it does not compile strangely.
import 'dart:convert';
import '...
0
votes
0
answers
109
views
Dart/Flutter - final unmodifiable list field
My app uses Flutter Bloc to manage app state. My state clas is defined as follows:
@immutable
@CopyWith()
class MyState extends Equatable {
const ReservationsState({
this.list1= const [],
...
1
vote
3
answers
93
views
How to do this in Kotlin?
I am trying to create a simple data class for a country.
data class Country(val name: String, val capital: String)
This works fine. Now I want to add neighbors.
data class Country(val name: String, ...
1
vote
0
answers
46
views
How to make Moose attributes immutable?
I would like to have immutable attributes in Moose. 'ro' takes care of this for scalar values and references, however, the inner workings of the reference are not affected by this write protection.
...
1
vote
2
answers
90
views
spark DF multiple Iterations on Rows
From the below data- col5 is holding the no of fruits to be distributed among plates from col1 to col4(4plates). Each time find the min from the plates(col1 to col4) add 1 fruit and reduce the fruit ...
0
votes
1
answer
57
views
How can I immutable update an array and store it in local storage in React?
I'm making a recipe app. I want useres to be able to add recipes to a list of favorites. There are 3 React components involved. Recipe, AddToFavorites, and Favorites.
The Recipe component shows ...
0
votes
0
answers
61
views
Jetpack Compose and MVI: Are mutable UI classes always bad?
Are there any valid reasons to make a UI data class property mutable?
For example: I have an app that allows users to send messages with polls with multiple choices using Checkboxes. I want ViewModel ...
0
votes
1
answer
110
views
How to prevent the mutation of nested prop fields in Vue 3, using TypeScript?
Suppose I have the following SFC component:
<script setup lang="ts">
export interface Person {
name: string;
}
const props = defineProps<{
person: Person;
}>();
function ...
0
votes
1
answer
38
views
Loop over Rust collection (borrowed immutably) then mutate it afterward
I'm having trouble while trying to manipulate a HashMap in Rust.
use std::os::fd::AsRawFd;
use std::collections::HashMap;
use std::collections::HashSet;
use tokio::net::TcpListener;
use tokio::sync::...
1
vote
1
answer
39
views
Can a unique identifier be applied to a Constructable Stylesheet?
Setup
User interaction may lead to one of several components being asynchronously injected into a document.
Each of these components has an associated Constructable Stylesheet.
But - and this is the ...
1
vote
1
answer
94
views
Parameter binding with immutable objects
I have doubts about this Standford University paper (I recommend it, I found it on the Internet), but a question arose about this code:
# parameters are passed via binding
def main():
original = [...
0
votes
1
answer
188
views
How to set VERSION-LEVEL IMMUTABILITY SUPPORT property of Azure storage Container using .Net Core
I am trying to set VERSION-LEVEL IMMUTABILITY SUPPORT property of container as below (C# with .Net Core) but none of them is setting this property to enabled. First and second are adding as metadata ...
0
votes
1
answer
64
views
Lazy var initialization error "Cannot use mutating getter on immutable value"
I tried two ways of initializing a lazy var, one works, the other gets a compiler error.
OK: var maxDiscount = MaxDiscount(); maxDiscount.maxDiscountPercent
ERROR: MaxDiscount().maxDiscountPercent
If ...
0
votes
0
answers
49
views
In Spark's Dataset<T>::map() function, can I mutate the object?
Spark's DataFrame, or Dataset<Row>, assumes that Row is immutable. I heard that the immutability is the foundation of failure tolerance, concurrency and optimizations.
But for a Dataset of a ...
0
votes
1
answer
101
views
Apollo immutability error - Cannot assign to read only property
I am trying wrap around the error thrown by the below code:
const [releaseHold] = useMutation(UPDATE_EMPLOYEE_STATUS, {
update(cache, { data: { employeeUpdateById } }) {
setLoading(false)
...
0
votes
1
answer
50
views
Classes common behavior + immutability in Kotlin
Is there a way to achieve the following but in a more immutable way?
abstract class Abstract {
abstract val general1: String
abstract var counter: Int // Don't want to use var here
fun ...
0
votes
0
answers
26
views
Python lambda function depending on parameter [duplicate]
I would like, for convenience, to define several functions as "slices" of a given one, along the following lines:
def f(x, k):
print(x, k)
gs = []
for k in range(2):
gs.append(...
0
votes
0
answers
30
views
Mutable references in rust and `&mut` [duplicate]
So I am reading through The Rust Programming Language book. Specifically, in this section it says the code
scores.entry(String::from("Blue")).or_insert(50);
"returns a mutable ...