我可以委托(delegate)给类中的构造函数参数
class SerialNumber(val value: String) : CharSequence by value {
init {
require(value.isNotBlank())
}
}
但是如果我让这个类成为一个值类
@JvmInline
value class SerialNumber(val value: String) : CharSequence by value {
init {
require(value.isNotBlank())
}
}
然后编译器说“如果表达式不是参数,值类不能通过委托(delegate)实现接口(interface)”
据我所知,value
是一个参数 - 发生了什么?
最佳答案
1.7.0 版本中启用了内联类的委托(delegate)实现
If you want to create a lightweight wrapper for a value or class instance, it's necessary to implement all interface methods by hand. Implementation by delegation solves this issue, but it did not work with inline classes before 1.7.0. This restriction has been removed, so you can now create lightweight wrappers that do not allocate memory in most cases.
问题在这里:https://youtrack.jetbrains.com/issue/KT-27435
在 Kotlin 1.7 之前,不可能通过委托(delegate)实现接口(interface),并且您会收到错误(正如您所注意到的,这是一个无意义的错误)。
如果您无法更新到1.7,您可以手动委托(delegate)该值。值得庆幸的是,Kotlin 通过利用扩展函数来保持较小的类占用空间,所以这非常简单!您只需要委托(delegate)一个属性和两个函数。
@JvmInline
value class SerialNumber(val value: String) : CharSequence {
init {
require(value.isNotBlank())
}
override val length: Int
get() = value.length
override operator fun get(index: Int): Char = value[index]
override fun subSequence(startIndex: Int, endIndex: Int): CharSequence =
value.subSequence(startIndex, endIndex)
}
关于kotlin - 为什么我无法委托(delegate)给 Kotlin 值类中的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72999689/