【问题标题】:Kotlin class delegation, passing this to delegateKotlin 类委托,将其传递给委托
【发布时间】:2018-05-07 21:07:13
【问题描述】:

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

class SomeFlow : Flow, SmsAuthentication by DefaultSmsAuthentication(this)

它说this 在这种情况下不存在。另一个类如下所示:

class DefaultSmsAuthentication(val flow: Flow) : SmsAuthentication

【问题讨论】:

  • 为什么需要这个?
  • 我有一些带有 SmsAuthenticationFlow 类的遗留代码。每个想要使用 sms auth 的流程都必须扩展此流程。我想把它委托给另一个班级。身份验证使用了一些流依赖项,尽管这让我意识到我只能传递这些依赖项......

标签: kotlin delegation


【解决方案1】:

通过setter而不是constructor注入this怎么样?

例如:

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)
    }

}

但是,您每次都需要在constructor 中手动调用withFlow()。你可能会忘记调用它。

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

class SomeFlow : Flow, SmsAuthentication {

    val auth by lazy { DefaultSmsAuthentication(this) }

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

}

你也可以反过来应用装饰器模式:

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()
}

【讨论】:

    猜你喜欢
    • 2012-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-12
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    相关资源
    最近更新 更多