在Kotlin中使用委派实现时传递此引用

问题描述

我正在使用Implementation by Delegation创建一种实体组件系统。

一个简化的示例:

// 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的构造函数PlainElectricComponent中使用'this' is not defined in this context错误。对this question的回答说,由于与JVM相关的限制,在对象构建的这一阶段不能使用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实现接口后,我可以充分使用编译器的类型检查,智能转换等功能

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)