我不太明白为什么我们可以在函数内部使用委托属性。我们无法在函数内部创建属性,因为在函数内部我们只能创建变量。
那么怎么可能在函数内创建委托属性呢?
这行代码是函数内的委托属性,我不明白为什么会这样。
val scoreFragmentArgs by navArgs<ScoreFragmentArgs>()
它有 getter 和 setter,但对我来说没有意义
Kotlin 委托基于存储委托对象,并委托对其进行更改的获取/设置。因此,在访问委托变量时可以内联
getValue
调用。
例如:
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
object Delegate : ReadOnlyProperty<Any?, Int> {
override fun getValue(thisRef: Any?, property: KProperty<*>): Int = 42
}
fun main() {
val foo by Delegate
println(foo)
}
Java 中的 main 方法如下所示:
static final KProperty[] $$delegatedProperties = new KProperty[]{(KProperty)Reflection.property0(new PropertyReference0Impl(Reflection.getOrCreateKotlinPackage(MainKt.class, "123"), "foo", "<v#0>"))};
public static void main() {
System.out.println(Delegate.INSTANCE.getValue(null, $$delegatedProperties[0]));
}
如您所见,访问变量被调用
getValue
所取代。