科尔廷班级代表团,将此传递给代表

时间:2017-11-23 21:10:48

标签: kotlin delegation

在kotlin委派课程时是否有可能通过this

class SomeFlow : Flow, SmsAuthentication by DefaultSmsAuthentication(this)

它说this在这种情况下不存在。另一个类看起来像这样:

class DefaultSmsAuthentication(val flow: Flow) : SmsAuthentication

1 个答案:

答案 0 :(得分:5)

如何通过setter注入this,而不是constructor

例如:

interface SmsAuthentication {

    fun withFlow(flow: Flow)

    fun auth()

}

class DefaultSmsAuthentication() : SmsAuthentication {

    var flow: Flow? = null

    override fun withFlow(flow: Flow) {
        this.flow = flow
    }

    override fun auth() {
        flow?.proceed()
    }

}

class SomeFlow : Flow, SmsAuthentication by DefaultSmsAuthentication() {

    init {
        withFlow(this)
    }

}

但是,您需要每次手动调用withFlow()中的constructor。你可能忘记打电话了。

您可能希望将SmsAuthentication作为财产。所以你只需要注入它by lazy并在需要时调用它。我认为这是更安全的方式。

class SomeFlow : Flow, SmsAuthentication {

    val auth by lazy { DefaultSmsAuthentication(this) }

    override fun auth() {
        auth.auth()
    }

}

您也可以应用Decorator模式,相反:

class DefaultSmsAuthenticationFlow(val flow: Flow) :
    SmsAuthentication,
    Flow by flow
{
    override fun auth() {
        // you can use flow as this here
    }
}

fun doAuth(flow: Flow) {
    DefaultSmsAuthenticationFlow(flow).auth()
}
相关问题