When creating a data class I frequently find that I want to transform one of the properties, usually to normalize it or to make a defensive copy. For example, here I want productCode
to always be lowercase:
data class Product(val productCode: String)
I've tried adding an init
block, in the hopes that Kotlin would be smart enough to let me manually deal with the assignment of the constructor parameter to the property:
data class Product(val productCode: String) {
init {
this.productCode = productCode.toLowerCase()
}
}
but it treats this as a reassignment.
I'd rather not have to write equals
/hashCode
/toString
/copy
by hand and IDE generated methods aren't really much better.
Is there any way to transform constructor parameters in a data class?