0

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.

Robin
  • 9,672
  • 6
  • 30
  • 49

2 Answers2

2

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.

Sweeper
  • 176,635
  • 17
  • 154
  • 256
0

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.

timj11dude
  • 31
  • 4
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/31647844) – A S M Sayem May 04 '22 at 19:22