Immutable, huge and nested objects

This is a common misunderstanding. If done correctly, making a change usually means N copies, where N is the depth of the change in your data structure, rather than copying the entire data structure. It’s typically not more than half a dozen modest allocations, usually less.

The thing is, you generally only do “shallow” copies at each level. So if one part of the structure has 20 fields under it, and you are changing 1 field, you reuse the other 19 in the new copy. (Since it is all immutable, this sort of reuse is safe, which it wouldn’t be in a mutable data structure.)

So while it’s not free, it usually isn’t terribly expensive. In my system, the core data structure is frequently a megabyte, made up of hundreds or thousands of sub-objects, and the immutable copy is still cheap enough to be a non-issue.

This is a key aspect of programming immutably. Immutable data structures (including Scala case classes) are generally designed so that the amount you have to actually copy when you make a change is minimized.

You may also want to look into a “lens” library such as Monocle, which can handle some of the boilerplate of deeply-nested fetches and copies.

1 Like