Is there any way to have a setter for a variable d...
# announcements
n
Is there any way to have a setter for a variable declared in the constructor? I have a data class where I must have a setter for one of the fields. Example:
Copy code
data class WTF(var name: String
                                  set(value) {
                                      println("This doesn't work 😞")
                                  }
                           )
r
Arguably that's not a data class, as it does more than just wrap data. Once you need to customize functionality, it's worth reconsidering if the
data
modifier still applies.
n
Doesn't
data class
just auto-implement
equals
,
hashCode
,
toString
and a copy function? This particular class is in an API. I have to check if the values provided to the setter are valid and throw an exception if they are not.
r
It does a few other things as well, but what it does is not the same as its purpose. From the docs:
We frequently create classes whose main purpose is to hold data. In such a class some standard functionality and utility functions are often mechanically derivable from the data. In Kotlin, this is called a data class ...
(see https://kotlinlang.org/docs/reference/data-classes.html) If you are changing how the data is set or retrieved, you're probably breaking the "mechanically derivable standard functionality" point of data classes.
g
I ran into a similar problem not too long ago. Ended up not using data classes. Wrote it up: http://gopalkri.com/2017/08/15/Kotlin-Data-Class-Constructor-Problem/ and http://gopalkri.com/2017/08/18/Kotlin-Data-Class-Constructor-Problem-Followup/
👍 2
g
could you override copy() ?
no, i guess not