Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to add a template to the getter/setter of a data class?

for example , I want to change all setters this way:

this.a = StringUtils.trim(a); 

If it's a java bean, I can do this by modifying the code generating template of the ide. But Intellij seems not support to atomically add getter/setter for kotlin data class.

Is there a way to do this?

like image 643
Mobility Avatar asked Dec 16 '25 13:12

Mobility


1 Answers

There is not a way to do this as of Kotlin 1.1.

A Kotlin data class, for the most part, is a class "to do nothing but hold data".

I think the closest you can get is to validate your data upon class initialization and make your data class properties read-only values. e.g.:

data class Data(val a: String) {
    init {
        require(a == a.trim())
    }
}

The following won't throw an exception:

val a = Data("ab")
val b = a.copy(a = "abc")

While the following will:

val c = a.copy(a = "abc ")
like image 126
mfulton26 Avatar answered Dec 19 '25 07:12

mfulton26



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!