https://kotlinlang.org logo
#announcements
Title
# announcements
n

nulldev

10/02/2017, 9:02 PM
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

Ruckus

10/02/2017, 9:13 PM
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

nulldev

10/02/2017, 9:32 PM
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

Ruckus

10/02/2017, 9:36 PM
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

gps

10/03/2017, 5:32 AM
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

gjesse

10/03/2017, 5:26 PM
could you override copy() ?
no, i guess not
3 Views