FAQ Database Discussion Community


How to update a field in a immutable object

java,oop,immutability
Supposing the following class: @Immutable public final MyMessageClass { private String message; private Date dateLastChange; private String identifier; public MyClass(final String message){ this.message = message; dataLastChange = new Date(); } public Date lastChange() { return new Date(dateLastChange.getTime()); } public String messageValue(){ return message; } } Once we have built an...

Dictionaries and lists appear immutable when passed to function

python,list,dictionary,immutability
I thought that dictionaries and lists were mutable in Python. What explains this behavior? #!/usr/bin/python3 def change_list(l): l = ['changed!'] def change_dict(d): d = {'changed!'} mydict = {'bob': ['blah', 5], 'asdf' : 'asdf'} change_dict(mydict) print(mydict) mylist = ['hello', 'foo', 'bar'] change_list(mylist) print(mylist) Output: $ python3 test3.py {'asdf': 'asdf', 'bob': ['blah',...

Integer variables pass by value, string variables by reference?

ruby,immutability
Modifications made to b below are also made to a: a = 'taco' b = a b << 's' a #=> tacos When I assign a variable x by pointing it at another variable y, x remains a shortcut to y; x and y will be identical. This seems confirmed...

How Instances of immutable types are inherently thread-safe

c#,thread-safety,immutability
I search about Why .NET String is immutable? And got this answer: Instances of immutable types are inherently thread-safe, since no thread can modify it, the risk of a thread modifying it in a way that interfers with another is removed (the reference itself is a different matter). So I...

Fill immutable map with for loop upon creation

scala,dictionary,collections,initialization,immutability
I have this map that looks like this: val fields: Map[(Int, Int), Field] and I thought about doing something like: val fields: Map[(Int, Int), Field] = Map( for(a <- 0 to 10) { (0, a) -> new Field(this, 0, a) } ) instead of a long copy/paste list like: (0,...

Mutable vs Immutable: how to implement editing user profile in functional\pure way?

haskell,design,functional-programming,immutability,purely-functional
I'm learning functional programming and try to apply its ideas in day job with imperative languages. My favourite idea is data immutability. I can apply this concept in my programs and try to make all my data structures and model objects immutable. But I have a standard feature in my...

Immutable Objects & Updates

java,database,hibernate,jpa,immutability
If I'm using an immutable class named Name that stores people's names, and someone wants to change their name shouldn't their name be updated (essentially delete the old entry and insert the new entry)? This appears to contradict the definition (by the annotation) of immutable as updating the entity will...

JavaScript - Why does the increment operator modify immutable strings?

javascript,string,immutability,nan
In JavaScript, strings are immutable. That means any operation on them returns a new object. Methods like trim, replace and slice don't modify the existing string. However, I was playing around in jsconsole and found an exception string = "string"; string + 37; => "string37" string; => "string" The original...

String immutable? [duplicate]

java,string,stack,heap,immutability
This question already has an answer here: Immutability of Strings in Java [duplicate] 10 answers Can anyone answer me please? public class ReplaceString{ public static void main(String arg[]) { String a = "Hariom"; a = a.replace('H', 'b'); System.out.println(a); } } ...

F# - Function not returning updated data

function,dictionary,f#,immutability,mutable
I have a function GetCars which does not return the updated state. If I add a parameter, it works fine, or if I execute the same code in the other functions it works fine. open System open System.Collections.Concurrent type Car = { Make : string Model : string ID :...

How to write an ImmutableMap that follows the Lisvok Subsitution and other SOLID principles without code smells?

java,interface,immutability,code-smell,lsp
I answered a question regaurding an ImmutableMap. I suggested using the Proxy pattern. The problem with this is that Map contains a put method, which would throw an UnsupportedOperationException. Replacing other instances of Map with ImmutableMap would break the Liskov Subsitution principle. Not only that, the need to declare put...

Immutable version of EnumSet

java,collections,set,immutability
I can't find an Immutable version of EnumSet. Two questions: Can I use Enums in a normal Guava ImmutableSet? If I can, what are some benefits/drawbacks of using an ImmutableSet instead of the EnumSet?...

How are Strings created and stored in Java?

java,string,memory-management,immutability,hashcode
To understand how String objects are created and stored, I tried the following program and I see output against which I have query. Can somebody please help? package corejava.immutable; public class StringTester { public static void main(String[] args) { // TODO Auto-generated method stub String s1 = "Omkar Patkar"; String...

What are the rules for tuple mutability?

swift,tuples,immutability
By trial&error I found some facts about tuples and mutability in Swift, but would like to learn about actual rules. Consider such code: class T { var f : String = "hello" } let a = T(); let b = (f : "hello", ""); a.f = "world"; b.f = "world";...

Are Elixir variables really immutable?

immutability,elixir
In Dave Thomas's book Programming Elixir he states "Elixir enforces immutable data" and goes on to say: In Elixir, once a variable references a list such as [1,2,3], you know it will always reference those same values (until you rebind the variable). This sounds like "it won't ever change unless...

Immutable Strings in Java - replace method works?

java,string,immutability
I understand that String is immutable. However, for this reason, I don't understand why the following code works (a code sample from Oracle). I refer to the line "path = path.replace(sep, '/');" Can someone please help explain? import oracle.xml.parser.v2.*; import java.net.*; import java.io.*; import org.w3c.dom.*; import java.util.*; public class XSDSample...

JavaScript security: force deletion of sensitive data

javascript,cordova,encryption,garbage-collection,immutability
Let's say that my app has a sensitive piece of data, e.g. an encryption key as it is performing local encryption/decryption, and I want the data to be completely flushed from my device's memory upon a logout. This would prevent my phone from falling into the wrong hands and someone...

what is “failure atomicity” used by J bloch and how its beneficial in terms of immutable object?

java,object,immutability,atomicity
just came across below statement as benefit of immutable object Immutable object always have “failure atomicity” (a term used by Joshua Bloch) : if an immutable object throws an exception, it’s never left in an undesirable or indeterminate state. can any one explain it in more detail and why is...

How does constructor-based dependency injection affects immutability?

java,spring,dependency-injection,immutability,constructor-injection
I am reading Spring documentation and I am wondering what they meant by writing: The Spring team generally advocates constructor injection as it enables one to implement application components as immutable objects and to ensure that required dependencies are not null. I don't see in what way does it enable...

Any way to use immutable.js with lodash?

javascript,reactjs,immutability,lodash,immutable.js
I'm using immutable.js with my flux application. It is very useful and gives performance boost. But what actually makes me sad is the fact that I can't use lodash together with it. Lodash provides great API with ton of useful functions, so I wonder maybe there is a way to...

non final - immutable classes

java,immutability,final
I have read and have always been told that immutable classes must be final . but i was wondering if it is possible to have a non final class object as immutable one. in this link (Why would one declare an immutable class final in Java?) what if the immutable...

Initializing an array with identical elements: `==` operator says arrays are the same, but they behave differently. Why?

ruby,immutability
Here's my code: a=["foo","foo","foo"] b=["foo"]*3 a==b # => true a.each{|i| i<<"bar"} b.each{|i| i<<"bar"} a==b # => false I get what I expect for a: ["foobar", "foobar", "foobar"] but for b, I get this: ["foobarbarbar", "foobarbarbar", "foobarbarbar"] Why is this happening? Is it a bug? Is there a way of filling...

In immutable class why fields are marked as private?

java,oop,field,private,immutability
What is the benefit of making fields private while creating an immutable class? I have seen why while creating immutable class, fields are declared as private? but I didn't get understand anything from this post. Can anybody please explain me the same?...

Convert immutable Bitmap file to mutable Bitmap

android,bitmap,immutability,mutable
A: Bitmap immutableBmp= BitmapFactory.decodeResource(getApplicationContext().getResources(),R.drawable.sample); mutableBitmap=immutableBmp.copy(Bitmap.Config.ARGB_8888, true); B: Bitmap immutableBmp= BitmapFactory.decodeFile(filePath); mutableBitmap=immutableBmp.copy(Bitmap.Config.ARGB_8888, true); C: BitmapFactory.Options options = new BitmapFactory.Options(); options.inMutable=true; myBitmap=BitmapFactory.decodeFile(filePath,options); A works but B and C don't. I am trying to convert a immutable bitmap to mutable. It works on...

How can I work around the immutability of a string in Javascript?

javascript,string,immutability
Since strings are immutable in Javascript, how can I use user's input for conversions? I was trying to use a function that changes an hexadecimal color code's digits into decimal numbers, but got stuck with the immutable property of strings. I tried copying each character to an array using "for",...

accessing old values of immutable strings

objective-c,nsstring,immutability
So I wrote this code: NSString *[email protected]"string 1"; NSString *[email protected]"string 2"; NSLog(@"str2 is: %@", str2); str2=[str1 stringByAppendingString:str2]; NSLog(@"str2 is: %@",str2); and it gave the following output: 2015-03-01 17:11:16.600 er[956:32910] str2 is: string 2 2015-03-01 17:11:16.601 er[956:32910] str2 is: string 1string 2 so str2 now points to different location in memory....

Is this compromise to string immutablity in java? [duplicate]

java,string,immutability,string-pool
This question already has an answer here: Is a Java string really immutable? 13 answers All of us know that String is immutable in java - content can not be changed once the string is created. String uses character array char[] value to store string content, here is the...

Spring DAO and immutable objects

java,spring,oop,immutability
According to the definition of a immutable object (see this question), I am not pretty sure about whether making setters of a Spring DAO as a only-one-use is a way to assure immutability or not. For instance (dataSource property): public class MySpringPojoDAO extends JdbcDaoSupport implements IMySpringPojoDAO { private boolean dataSourceSet...

Immutability as applied to classes

c#,immutability
I have been reading about immutable types, and how that it is not recommended to have a mutable struct. What if I have a class instead: public class Vector { public double X, Y; public void Rotate(double angle) { double x = this.X; double y = this.Y; this.X = (float)((Math.Cos(angle)...

Memory consumption when chaining string methods

c#,string,immutability,method-chaining
I know that string in C# is an immutable type. Is it true that when you chain string functions, every function instantiates a new string? If it is true, what is the best practice to do too many manipulations on a string using chaining methods?...

Swift error: Cannot assign to immutable value

osx,swift,immutability
I got the error above for that code snippet: func store(name: String, inout array: [AnyObject]) { for object in array { if object is [AnyObject] { store(name, &object) return } } array.append(name) } Any ideas?...

PHP pass objects by value

php,immutability,purely-functional
I'd like to implement a pure function in PHP How do I pass an object by value and not by reference In other words, this is the expected output function change($obj) { $obj->set_value(2); } $obj=new Object(); $obj->set_value(1); change($obj); echo $obj->get_value();//1 ...

BSTD inorder traversal produces erroneous behaviour

java,debugging,recursion,immutability
I have a BSTD implementation which is inserting values incorrectly and I can't find for the life of me what is going on. EXPECTED ACTUAL -------- ---------- Alex Janice Carlos Janice Elton Janice Janice Zidane Zidane Zidane Implementation private Node<K,E> insert(Node<K,E> node, K key, E elem) { if (node ==...

Mutability of string when string doesn't change in C#?

c#,string,immutability,stringbuilder,mutable
If the string operation doesn't change the value of string, Will that end up in creation of new instance?Eg; string str="foo"; str+=""; i know the difference between string and stringbuilder in C#....

Immutable `var` array

swift,immutability
I'd like to create an array in Swift that is immutable, but can be completely replaced, in the style of functional programming. I understand that I can create them in this way: var mutable = [1,2,3] // can change reference, add, remove, etc let immutable = [4,5,6] // cannot replace...

What is the difference between member val and member this in F#?

.net,f#,immutability
When I created a class containing a generic, mutable .NET Stack in F# like the example below, that stack ignores anything I push onto it. open System.Collections.Generic type Interp(code: int array) = member val PC = 0 with get, set member this.stack: Stack<int> = new Stack<int>() member this.Code = code...

C# Immutable class sub class

c#,inheritance,immutability
I have a type that is an immutable type, and I'd like to create a subclass of it that has access to all the same methods. However, because of how you have to implement an immutable class, the base class methods return my parent type, not my child type. Is...

Scala: How to compute the sum of all elements in the leaves of a Binary Tree?

scala,sum,binary-tree,immutability,case-class
I'm learning Scala by working the exercises from the book "Scala for the Impatient". Given the following way to model binary trees with case classes, one question asks to compute the sum of all elements in the leaves. sealed abstract class BinaryTree case class Leaf(value: Int) extends BinaryTree case class...

In D, how can I declare a hash of immutable types that is itself mutable?

d,immutability
I believe I was able to do this in an earlier version of the language, and indeed, code I wrote several months ago, which compiled fine then, does not compile now. Example: immutable(X)[int] myhash; myhash[5] = some_immutable_X; //previously fine. myhash[5] = some_other_immutable_X; //previously fine also. Now however, dmd complains with...

How to compose mutable Iterators?

iterator,rust,immutability,lifetime
I would like to make an iterator that generates a stream of prime numbers. My general thought process was to wrap an iterator with successive filters so for example you start with let mut n = (2..N) Then for each prime number you mutate the iterator and add on a...

Is it possible to make a third-party mutable struct “more immutable” via F#?

c#,f#,immutability,mutable,third-party-code
For example, wouldn't this type: https://msdn.microsoft.com/en-us/library/microsoft.xna.framework.vector2.aspx ... having public mutable fields like this: https://msdn.microsoft.com/en-us/library/microsoft.xna.framework.vector2.x.aspx ... single-handedly make consuming F# code's immutability efforts kind of useless? PS: performance must be preserved, no wrapping or dynamic instantiation of throw-away values. PPS: I did some research and suspect the answer (negative) but would...

Mutable references to immutable data in Haskell

haskell,immutability,frege
I'd like to keep track of a "current" value in a succession of immutable values. What is the best way to do that in Haskell without introducing a new reference for every new value? Here is an example: data Person = Person {name, level, topic :: String } deriving(Show) dierk...

Haskell list manipulation performance

haskell,immutability,haskell-platform
I am currently learning Haskell and I am curious about the following: If I add an element to a List in Haskell, Haskell returns a (completley?) new list, and doesn't manipulate the original one. Now let's say I have a List of a million elements and I append one element...

How to generate data idiomatically in f# inline in code

f#,functional-programming,immutability,poker
Lets say i am attempting to implement some sort of poker program in f#. Firstly is this the correct use of the type system, massive newbie here. type Suit = | Hearts | Diamonds | Spades | Clubs type Card = { Suit:Suit Rank:int } type Hand = { Cards:List<Card>...

Should an object always encapsulate the data that its methods work on?

php,oop,design-patterns,immutability
I'm developing a PHP class, RequestSanitize, that will process some raw user input. One way I could do it is: class DataSanitizer implements DataSanitizerInterface { protected $_schema; public function __construct($schema){ $this->_schema = $schema; // Blah blah blah } public function sanitize($data) { $sanitizedData = []; // Blah blah blah populate...

Ways to signal that API returns an unmodifiable/immutable collection

java,immutability
Other than documenting it (obviously it should also be documented), using a special return type (I'm wary of limiting myself to an ImmutableX) or having the user find out at runtime, is there any other way of telling the users of an API that the collection they receive from said...

Are the objects in the following class immutable?

java,multithreading,class,immutability,mutable
public class Point { private double x; private double y; Point (double x, double y) { this.x = x; this.y = y; } double getX() { return x; } double getY() { return y; } } Are the objects in the above class immutable? Explain. I am getting confused because...

Looking for usable immutable bool array in C#

c#,arrays,immutability,immutable-collections
I have a class which has an bool array member. If I modify an element of this array, a new modified copy of the instance should be created. Sounds like a perfect opportunity for using an Immutable type. Googling around showed that Microsoft provides a new library Immutable Collections which...

Multiplying two numbers by successive sums in F#

f#,functional-programming,immutability
Giving m and n as integers, I can multiply them by successive sums like this: m * n = m + m + m + ... + m (n times) So, let's consider the pseudo code below: m = ... (first number) n = ... (second number) Result = 0;...

Should every object in the store state be immutable?

javascript,reactjs,immutability,flux,immutable.js
I am learning React.js and Flux, and I understand that is better to keep the object immutable because comparing them is O(1). My situation is this: I have a store, which has a _state object, that is a map (I'm using Immutable-js). That _state has some booleans, some strings and...

Does using private setters only in a constructor make the object thread-safe?

c#,thread-safety,immutability
I know that I can create an immutable (i.e. thread-safe) object like this: class CantChangeThis { private readonly int value; public CantChangeThis(int value) { this.value = value; } public int Value { get { return this.value; } } } However, I typically "cheat" and do this: class CantChangeThis { public...

How to throw away the original collection once the Immutable version is created using Google Guava?

java,guava,immutability
I have a map as below and once I get the immutable version of the original map, I don't need the original one anymore. Is there a way to have the GC recycle it? Map<String, String> map = new TreeMap<>(); map.put("1", "one"); map.put("2", "two"); map.put("3", "three"); ImmutableMap<String, String> IMMUTABLE_MAP =...

How to get union of several immutable.js Lists

javascript,node.js,list,immutability,immutable.js
So, I have List a: let a = Immutable.List([1]) and List b: let b = Immutable.List([2, 3]) I want to get List union === List([1, 2, 3]) from them. I try to merge them fist: let union = a.merge(b); // List([2, 3]) It seems like merge method operates with indexes,...

What is this thing called in Java?

java,oop,object,inheritance,immutability
Google isn't being very friendly today, and I'm researching some OOP techniques I've not used in the past. Basically, I've noticed some libraries have variables with preset choices, like new Website(Websites.STACKOVERFLOW). What is that called, when you've got apparently immutable values like that? What if I want to create my...

Immutable class in Java

java,class,immutability,final
As per many documentations, I have seen that an immutable class should have the following features: class should be final all the methods should be final all the variables should be final there should not be any setters But my questions are: What if I have a class with only...

How to make the below java class Immutable

java,immutability
Is there anything else to do to make the below class immutable apart from the following. No Setters All fields are private and final Class is declared as final so methods cannot be overridden in subclass public final class ImmutableClass { private final String name; private final List<Integer> listOfNumbers; public...

How to decorate an immutable object graph from scala case classes

json,scala,playframework,immutability,case-class
I'm reading structured JSON, using Play Frameworks' JSON Reads to build up an object graph with case classes. An example: case class Foo ( id: Int, bar_id: Int, baz_id: Int, x: Int, y: String ) { var bar: Bar = null var baz: Baz = null } After building the...

Java immutability when defining members in a function called by constructor

java,class,design-patterns,design,immutability
I have class like this: abstract class Parent { protected Parent(Raw rawData) { deserialize(rawData); } protected abstract void deserialize(Raw rawData); } class Child extends Parent { final byte firstByte; public Child(Raw rawdData) { super(rawData); } protected void deserialize(Raw rawData) { firstByte = rawData.getFirst(); } } So basically any child class...

How to create any kind of immutable providers in AngularJS

angularjs,immutability,angularjs-provider
Consider the following example: angular.module('demo') .service('MyService', function () { this.fn = function () { console.log('MyService:fn'); }; }) .factory('MyFactory', function () { function fn() { console.log('MyFactory:fn'); } return { fn: fn }; }) .value('MyValue', { fn: function () { console.log('MyValue:fn'); } }) .constant('MyConstant', { fn: function () { console.log('MyConstant:fn'); } })...

Is there a way to make the @Builder annotation work for immutable classes?

groovy,immutability,builder
I'm trying to develop a project in Groovy and I've been looking through my code and trying to find areas which I could replace with something more idiomatically Groovy until I find a solution for another issue I've been having. I've started taking a more in-depth look into the use...

Jackson deserialization circumventing final fields

java,json,jackson,immutability,lombok
Here's the code import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.Data; import lombok.ToString; public class Main { public static void main(String[] args) throws Exception { Fields f1 = new Fields(1); System.out.println(f1); ObjectMapper mapper = new ObjectMapper(); String str = mapper.writeValueAsString(f1); System.out.println(str); Fields f2 = mapper.readValue(str, Fields.class); System.out.println(f2); } @Data @ToString public static...

Converting mutable java classes to immutable scala classes

scala,immutability
I have a class which functions something like this class OutputFile(name: String, index: Int = 0){ val localFile = File.createTempFile(name, ".gz") localFile.deleteOnExit() val localFileOut =new FileOutputStream(localFile) private[this] var bytesWritted: Int = 0 def write(line: Bytes): OutputFile = { if(bytesWritten > SOMESIZE) flush //this function uploads the file to a different...

How to create a map of records from a javascript raw object with Immutable.js?

javascript,immutability,immutable.js,reviver-function
I'm new to immutable.js and I'd like to understand better how to use records starting from a raw JS object. With Immutable.fromJS() I can create a map passing a raw object, for example: var images = { "1": { id: "1", urls: ["/medium/1.jpg", "/large/1.jpg"] }, "2": { id: "2", urls:...

What are some common uses of immutable data structures?

javascript,frontend,immutability,immutable.js
What motivates the increasing usage of immutable data structures such as those provided in ImmutableJS and SeamlessJS? I know there are debugging and memory benefits. I'm interested in uses across the JavaScript stack, but I'm also thinking of common front-end tasks that are made easier to work with or reason...

Cannot borrow as immutable - String and len()

rust,immutability,mutability,borrow-checker
let mut result = String::with_capacity(1000); result.push_str("things... "); result.push_str("stuff... "); result.truncate((result.len() - 4)); However, this is a compile error. Something to do with the borrow checker and possibly mutability. multipolygon.rs:63:21: 63:27 error: cannot borrow `result` as immutable because it is also borrowed as mutable multipolygon.rs:63 result.truncate((result.len() - 2)); ^~~~~~ multipolygon.rs:63:4: 63:10...

Override returned reference of object

javascript,immutability
I was recently looking into Facebook's Immutable-JS library, and saw the following interesting behaviour: var map1 = Immutable.Map({a:1, b:2, c:3}); var clone = map1; The library ensures that map1 !== clone. How is this achieved? I suspected that it is possible to override a property method that retrieves the object's...