2017-11-23 6 views
0

kotlinでクラスを委任するときにthisを渡す可能性はありますか?Koltinクラスの委任代理人にこれを渡す

class SomeFlow : Flow, SmsAuthentication by DefaultSmsAuthentication(this) 

それはthisは、このコンテキスト内に存在しないと言います。他のクラスには、次のようになります。

class DefaultSmsAuthentication(val flow: Flow) : SmsAuthentication 
+2

あなたがこれを必要とするのはなぜ? – funivan

+0

私はSmsAuthenticationFlowクラスでいくつかのレガシーコードを持っています。 sms authを使用するすべてのフローは、このフローを拡張する必要があります。私は別のクラスにそれを委託したいと思います。認証はいくつかのフロー依存関係を使用しますが、私はそれらの依存関係のみを渡すことができると気付きます... –

答えて

3

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

} 

はしかし、あなたは毎回手でconstructorwithFlow()を呼び出す必要があります。あなたはそれを忘れるかもしれません。

プロパティとして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() 
} 
関連する問題