首页 > 解决方案 > 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()
    }
}

这样的事情可能吗?

标签: kotlindelegates

解决方案


我想你想要的是这样的:

class Supervisor : Worker by Delegate(){
    
}

推荐阅读