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)
我try 添加一个init
%的挡路,希望Kotlin 足够聪明,让我手动处理构造函数参数对属性的赋值:
data class Product(val productCode: String) {
init {
this.productCode = productCode.toLowerCase()
}
}
but it treats this as a reassignment.
我宁愿不必手工编写equals
/hashCode
/toString
/copy
,IDE生成的方法也不会更好.
Is there any way to transform constructor parameters in a data class?