Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How deep would you expect the immutability of an immutable list to be?

If you have an immutable list, you expect it to always return a reference to the same object when you ask for, say

list.get(0)

My question is, would you expect to be able to mutate the object and have the mutation reflected next time you get it from the list?

like image 827
jjujuma Avatar asked Apr 09 '09 09:04

jjujuma


4 Answers

It depends on the context. In a general purpose library, all we should assume is that the list is immutable. Changes to the elements in the list would be reflected to all callers, as a direct consequence of returning the same reference each time.

However, if this is a specialized immutable tree (or whatever), and is documented as such then you would expect the items in the list to themselves be immutable, and it becomes a moot question.

like image 138
Marc Gravell Avatar answered Oct 31 '22 18:10

Marc Gravell


The question if not about the immutability of the list, but about the immutability of the objects contained.

In fact, if you have reference types, the immutable entity in the list is the reference. This means that the reference will always be the same. Now whether the referenced object changes only depends on what kind of object it is. If the object is immutable (like, for instance, strings in both .NET and Java, or all value types in .NET), the object cannot change.

Otherwise, the object can change and all other references to the same object will see the changed state, since they hold a reference to the same instance. Therefore, as I wrote in the beginning, this is completely independent of the list (and whether it is immutable or not).

like image 40
Lucero Avatar answered Oct 31 '22 17:10

Lucero


That's usually to be expected. The list is immutable, which means you cannot add or remove items in it or replace items entirely. If you want those items to be immutable you have to take care of that yourself. The list certainly can't stop you from mutating the object's state once you got a reference to it.

like image 24
Joey Avatar answered Oct 31 '22 16:10

Joey


Yes.

I don't expect an immutable list to clone its objects when I get them, unless it is documented as doing so.

like image 41
Stephen Denne Avatar answered Oct 31 '22 18:10

Stephen Denne