kotlin - 在 Kotlin 中使用委托实现时传递此引用
问题描述
我正在使用委托实现来创建一种实体组件系统。
一个简化的例子:
// attribute 1: can take damage
interface Damageable {
val broken: Boolean
fun takeDamage(dmg: Int)
}
// simple implementation
class HpComponent(private var hp: Int): Damageable {
override val broken: Boolean
get() = hp <= 0
override fun takeDamage(dmg: Int) {
hp -= dmg
}
}
// attribute 2: something with electricity
interface Electric {
fun overcharge()
}
// implementation where overcharge damages the component
class PlainElectricComponent(private val component: Damageable): Electric {
override fun overcharge() {
component.takeDamage(10)
}
}
// oven entity
class Oven: Damageable by HpComponent(hp=20), Electric by PlainElectricComponent(this)
编译器给了我一个在:this
的构造函数中使用的错误。这个问题的答案说,由于 JVM 相关的限制,在对象构造的这个阶段使用指针是不可能的。PlainElectricComponent
'this' is not defined in this context
this
我知道我可以component
稍后进行初始化,例如通过
class PlainElectricComponent: Electric {
lateinit var component: Damageable
...
}
class Oven(private val ec: PlainElectricComponent = PlainElectricComponent()):
Damageable by HpComponent(hp=20),
Electric by ec
{
init {
ec.component = this
}
}
但这会强制构造一个丑陋的构造函数,并且需要额外的“接线”,这很容易被遗忘。
您是否知道另一种方法可以让实体的组件声明保持直截了当?
PS:Oven
实现接口后,我可以充分使用编译器类型检查、智能转换等。
解决方案
推荐阅读
- microsoft-graph-api - "表达式 \"fields(select\" 无效。"
- json - 如何从柏树测试中获取数据到 JSON 文件中?
- c# - 使用 .NET 反序列化 JSON
- javascript - 如何根据 react-native 中的条件导出对象?
- android - Android Studio 4.1 Canary:Firebase Crashlytics 破坏 android 项目编译
- javascript - 服务发出更改时组件模板变量不更新(角度)
- apt - mv:无法统计“pencil.desktop”:没有这样的文件或目录
- java - 如何使用 SDK 从 Android POS 中的内置打印机进行打印?
- c++ - C ++ dyld:未加载库 - 设置'-L'后
- python - 连接到 mysql 数据库时出现超时错误(更新)