kotlin - Kotlin 委托与 `by` 但在 *inside* 委托人中创建委托
问题描述
我想使用 Kotlin 委托,但我不想在委托人之外创建委托。委托的所有示例都如下所示:
interface Worker {
fun doWork()
}
class Supervisor(workerDelegate: Worker) : Worker by workerDelegate {
}
class Delegate : Worker {
override fun doWork() {
// actual work
}
}
fun main() {
val delegate = Delegate()
val supervisor = Supervisor(delegate)
supervisor.doWork() // delegates to delegate
}
但我想在Delegate
里面创建Supervisor
. 像这样的东西:
class Supervisor : Worker by workerDelegate {
init {
val workerDelegate = Delegate()
}
}
这样的事情可能吗?
解决方案
我想你想要的是这样的:
class Supervisor : Worker by Delegate(){
}
推荐阅读
- django - Django get_absolute_url() 似乎在评论部分不起作用
- visual-c++ - 无法通过 VC++ 获取和导出 PowerPoint 中的每张幻灯片
- c++ - 如何在依赖于就地构建的 Python 项目中使用 Sphinx?
- json - 如何使用 | 安全地运行 jq 命令 (管道)字符?
- javascript - 如何通过代码重启 Nodemon 服务器?
- c - 什么是指针,它的类型是什么?
- delphi - 使用 libvlc 播放 wav 文件会丢失开头或结尾
- django - 电子邮件在开发中发送,但不在生产中
- web-scraping - 将网页中的工具提示导入 Google 表格
- qiskit - 使用 qiskit_textbook 包