kotlin - 这不是指使用 Kotlins 类委托的原始对象
问题描述
我很困惑委托在 Kotlin 中的工作方式。维基百科说:
借助语言级别的委托支持,这是通过让委托中的 self 引用原始(发送)对象而不是委托(接收对象)来隐式完成的。
给定以下代码:
interface BaseInterface {
fun print()
}
open class Base() : BaseInterface {
override fun print() { println(this) }
}
class Forwarded() {
private val base = Base()
fun print() { base.print() }
}
class Inherited() : Base() {}
class Delegated(delegate: BaseInterface) : BaseInterface by delegate
fun main(args: Array<String>) {
print("Forwarded: ")
Forwarded().print();
print("Inherited: ")
Inherited().print();
print("Delegated: ")
Delegated(Base()).print();
}
我得到这个输出:
Forwarded: Base@7440e464
Inherited: Inherited@49476842
Delegated: Base@78308db1
我希望 Delegated 返回Delegated
,因为 self/this 应该引用原始对象。我弄错了还是 Kotlins 代表团不同?
解决方案
Kotlin委托非常简单 - 它生成所有接口方法并在委托对象上隐式调用它,但用户显式覆盖的方法除外。
您的示例在功能上与:
class Delegated(delegate: BaseInterface) : BaseInterface{
// when generating bytecode kotlin assigns delegate object to internal final variable
// that is not visible at compile time
private val d = delegate
override fun print(){
d.print()
}
}
所以很清楚为什么会打印Base
.
推荐阅读
- opencv - 如何从单个 PNG 中分离大小为 8 和 16 的两个位图
- html - css 动态 nth-child 选择器
- docker - docker compose up 无法挂载卷
- javascript - 如何处理 React Router 递归路径?
- elixir - 如何在 Phoenix LiveView 中测试 handle_info/2?
- azure - 如何从不同的变量组 Azure Pipeline 访问相同的变量?
- c# - 数据绑定不适用于在 ItemsControl 中用作 DataTemplter 的 UserControl
- python - 导入本地 .py 文件时如何确保导入包
- java - 无法使用 Mockito 模拟带注释的字段
- flutter - Flutter:如何创建上一个和下一个项目较小的 PageView?