微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决在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 举报,一经查实,本站将立刻删除。