Nice way of copying an immutable value while changing only a few of its many properties?

I meant something a little different, that is, "extension" as in "adding a method to an arbitrary type", rather than "defining a protocol and making an arbitrary type conform to it".

For example, in pseudo-swift:

extension Any {
    func with(_ modify: (inout Self) throws -> Void) rethrows -> Self {
        var copy = self
        try modify(&copy)
        return copy
    }
}

This would add a with method to everything, without the need to define a protocol and manually conforming types to it. I understand that writing extension Foo : CopyableWithModification {} for each type doesn't require much effort, but I still find easier and faster to just use a global with function.

2 Likes