问题
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