kotlin how to refer outer-scope this in multi-layer apply functions

北城余情 提交于 2019-12-06 21:52:12

问题


for example:

 v1?.apply {
       v2?.apply {
           call(this, target, outerThis);
       }
    }

my question is how to refer to "outerThis"? thanks for any help.


回答1:


You can use a label and then a qualified this expression:

v1?.apply outer@ {
    v2?.apply {
        call(this, target, this@outer)
    }
}



回答2:


It's generally not recommended to use nested apply calls, which is to avoid your situation. You may of course use labels as a workaround, but you may also use also as an alternative:

v1?.also { outer ->
    v2?.apply { 
        call(this, target, outer)
    }
}

This prevents the usage of a label, which is often frowned upon. There is nothing wrong with labels though.

Note: also is a new addition to the stdlib in kotlin 1.1. If you are using older version you may not be able to see it. Either update kotlin to 1.1 or add this piece of code anywhere in your module:

inline fun <T> T.also(block: (T) -> Unit) { block(this) }


来源:https://stackoverflow.com/questions/44779568/kotlin-how-to-refer-outer-scope-this-in-multi-layer-apply-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!