kotlin - 为什么我无法委托(delegate)给 Kotlin 值类中的参数?

标签 kotlin

我可以委托(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)实现

https://kotlinlang.org/docs/whatsnew17.html#allow-implementation-by-delegation-to-an-inlined-value-of-an-inline-class

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/

相关文章:

android - RecyclerView 在开始时闪烁数据使行不可见

java - 基于 Kotlin 的应用程序将在 Android P 上获得性能提升意味着什么

mongodb - 是否可以通过 gradle (Kotlin-DSL) 为 Kotlin MongoDB 文档生成 Q 类?

Android 3.6 ViewStubProxy 未解析引用

kotlin - 如何反序列化格式为 "yyyy-mm-dd hh:mm:ss"的日期?

jdbc - Kotlin:创建自定义的CoroutineContext

android - Kotlin 静态函数 : companion object, @JvmStatic @JvmField

kotlin - Unresolved reference : Callback

android-studio - Kotlin,Android,如何正确调试协程?

json - 使用Android Studio 3.0时如何存储json数据?