是否从官方文档中复制/粘贴: 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 Compose
:https://stackoverflow.com/a/63877349/10777336
答案 0 :(得分:2)
文档中的代码仅适用于 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+。