【问题标题】:Official documentation code gives `Type 'KProperty0<Int>' has no method 'getValue(MyClass, KProperty<*>)' and thus it cannot serve as a delegate`官方文档代码给出了 `Type 'KProperty0<Int>' has no method 'getValue(MyClass, KProperty<*>)' 因此它不能用作委托`
【发布时间】:2021-06-20 05:47:33
【问题描述】:

从官方文档中复制/粘贴: https://kotlinlang.org/docs/delegated-properties.html#delegating-to-another-property

var topLevelInt: Int = 0
class ClassWithDelegate(val anotherClassInt: Int)

class MyClass(var memberInt: Int, val anotherClassInstance: ClassWithDelegate) {
    var delegatedToMember: Int by this::memberInt
    var delegatedToTopLevel: Int by ::topLevelInt

    val delegatedToAnotherClass: Int by anotherClassInstance::anotherClassInt
}
var MyClass.extDelegated: Int by ::topLevelInt

还有一个错误:

我想我需要导入一些包,就像这个答案一样,但是对于Intellij,而不是Jetpack Composehttps://stackoverflow.com/a/63877349/10777336

【问题讨论】:

  • 我刚刚在Play Kotlin 中尝试过,它成功了。你的 Kotlin 版本是什么?
  • 哦,原来是 1.3,我把它改成 1.5 就可以了。谢谢!

标签: kotlin


【解决方案1】:

文档中的代码仅适用于 Kotlin 1.4+ 版本。来自What's New 1.4

更好地推断委托属性

在分析 by 关键字后面的委托表达式时,没有考虑委托属性的类型。比如下面这段代码之前没有编译过,现在编译器可以正确推断出新旧参数的类型为String?:

import kotlin.properties.Delegates

fun main() {
    var prop: String? by Delegates.observable(null) { p, old, new ->
        println("$old → $new")
    }
    prop = "abc"
    prop = "xyz"
}

所以你应该把你的 Kotlin 版本更新到 1.4+。

【讨论】:

    猜你喜欢
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多