gpt4 book ai didi

kotlin - 为什么委托(delegate)类方法getValue 和setValue 需要用operator 关键字标记?

转载 作者:行者123 更新时间:2023-12-05 01:56:36 24 4
gpt4 key购买 nike

这是来自 Delegated properties 的示例文档。

import kotlin.reflect.KProperty

class Delegate {
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
return "$thisRef, thank you for delegating '${property.name}' to me!"
}

operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
println("$value has been assigned to '${property.name}' in $thisRef.")
}
}

最佳答案

这是因为委托(delegate)属性是 defined by convention .这意味着:

[its] semantics are defined through syntactic expansion of one syntax form into another syntax form.

可以看到委托(delegate)属性的扩展further down the documentation page :

class C {
var prop: Type by MyDelegate()
}

// this code is generated by the compiler instead:
class C {
private val prop$delegate = MyDelegate()
var prop: Type
get() = prop$delegate.getValue(this, this::prop)
set(value: Type) = prop$delegate.setValue(this, this::prop, value)
}

按照惯例定义的语法的一个特征是(来自第一个链接):

All call expressions that are produced by expansion are only allowed to use operator functions.

还有:

This expansion of a particular syntax form to a different piece of code is usually defined in the terms of operator functions.

只是为了给您提供更多示例,第一个链接显示了更多按约定定义的语法示例。下面是与它们相关的相应算子函数:

<表类="s-表"><头>约定的语法相关算子函数<正文>算术和比较运算符 plus, compareTo调用约定 调用运算符形式赋值 plusAssign, minusAssign 等For 循环语句 迭代器, hasNext, next委托(delegate)属性 设置值, 获取值解构声明 component1, component2

请注意,您需要在所有这些函数上加上单词 operator 才能使相应的语法起作用。换句话说,“operator”表示该函数可以在约定定义的语法中使用。

关于kotlin - 为什么委托(delegate)类方法getValue 和setValue 需要用operator 关键字标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69768818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com