You are currently viewing How to make an update function for a class that returns a new class of this type?

How to make an update function for a class that returns a new class of this type?

Let’s say I have a class foo that has a property sum and a really expensive init block.

class Foo(val sum) { init { ... } } 

I want to have an update function that takes a parameter and makes that the new sum. However, I don’t like mutable state, so instead of making sum a var and having update changing it, I want to return a new foo with the changed sum. However, if I were to do it like:

update(newSum:Int):Foo { val result = Foo(newSum) return result } 

I would call the expensive init function again. Is there some nice way to do this type of immutable structure that returns its updated self that I’m missing, or do I just need to rethink my approach entirely?

submitted by /u/Acidic_Jew2
[link] [comments]