Issue
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
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.
Answered By - Sweeper
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.