首页 > 解决方案 > 在 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 contextthis

我知道我可以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实现接口后,我可以充分使用编译器类型检查、智能转换等。

标签: kotlindelegationentity-component-system

解决方案


推荐阅读