'How to modify the parameter pass to kotlin data class?

Say I have a data class

data class MyClass(val crop: Rect, val name: String)

But I want to make a copy of the Rect passed in since I don't want the value to be modified later. I don't want to the caller to call

MyClass(Rect(inCrop), "name")

in the code. How can I do this in my data class?

Thanks.



Solution 1:[1]

One workaround I can think of is:

data class MyClass(private var privateCrop: Rect, val name: String) {
    val crop get() = privateCrop

    init {
        privateCrop = Rect(privateCrop)
    }
}

You make crop private and make it a var (privateCrop), then you add a public getter for it. Now you can copy it in an init block.

But I gotta admit, this is rather ugly. The better solution here I think is to change Rect to be immutable, but if Rect isn't in your control, then I guess it can't be helped. You might also consider using a regular class.

Solution 2:[2]

You may not want to alter data class's like this. As per another solution's answer, you may find other peculiarities with this solution. The solution given by @Sweeper, also does not include providing a defensive copy, which you may want to do to avoid access to modifying the internal property field.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 timj11dude