gpt4 book ai didi

kotlin - 有没有办法在数据类构建时转换属性的值?

转载 作者:IT老高 更新时间:2023-10-28 13:39:47 26 4
gpt4 key购买 nike

在创建数据类时,我经常发现我想转换其中一个属性,通常是对其进行规范化或制作防御性副本。例如,这里我希望 productCode 始终为小写:

data class Product(val productCode: String)

我尝试添加一个 init block ,希望 Kotlin 足够聪明,让我手动处理将构造函数参数分配给属性:

data class Product(val productCode: String) {
init {
this.productCode = productCode.toLowerCase()
}
}

但它将此视为重新分配。

我宁愿不用手动和 IDE 编写 equals/hashCode/toString/copy生成的方法并没有好多少。

有什么方法可以转换数据类中的构造函数参数吗?

最佳答案

没有。要使相等和 toString 起作用,属性需要位于 the primary constructor 中。 .

然而,你可以做的是创建一个工厂方法:

data class Product private constructor(val productCode: String) {

companion object Factory {
fun create(productCode: String) : Product {
return Product(productCode.toLowerCase())
}
}
}

通过使构造函数 private 你强制使用这个 create 方法。

如果您想获得“hacky”,您可以假装您仍在调用构造函数,方法是将 create 重命名为 invoke 和使其成为 operator 函数:

data class Product private constructor(val productCode: String) {

companion object {

operator fun invoke(productCode: String): Product {
return Product(productCode.toLowerCase())
}
}
}

调用 Product("foo") 将调用 invoke 方法。


注意:构造函数还是通过copy方法暴露出来的,见https://youtrack.jetbrains.com/issue/KT-11914

关于kotlin - 有没有办法在数据类构建时转换属性的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49561735/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com