如何在范围内使"this"引用Kotlin Android Extension类型类?



我有一个代码如下

recycler_view.apply {
// Some other code
LinearSnapHelper().attachToRecyclerView(this)   
}

如果我想使用apply,以下this是错误的

recycler_view.apply {
// Some other code
LinearSnapHelper().apply {
.attachToRecyclerView(this) // This will error because `this` is LinearSnapHelper()
}
}

我试过this@RecyclerView仍然错误

recycler_view.apply {
// Some other code
LinearSnapHelper().apply {
.attachToRecyclerView(this@RecyclerView) // Still error
}
}

我试过this@recycler_view仍然错误

recycler_view.apply {
// Some other code
LinearSnapHelper().apply {
.attachToRecyclerView(this@recycler_view) // Still error
}
}

引用this的语法是什么recycler_view

注意:我可以执行以下操作,但只是想学习如何在 Kotlin Android 扩展类型类apply中拥有this

recycler_view.apply {
// Some other code
LinearSnapHelper().apply {
// Some other code
}.attachToRecyclerView(this)
}

在这种情况下,您可以将显式标签应用于外部 lambda:

recycler_view.apply recycler@{
// Some other code
LinearSnapHelper().attachToRecyclerView(this@recycler)   
}

但是,嵌套apply块看起来并不习惯并且可能会令人困惑,我建议对recycler_view使用其他范围函数,例如let

recycler_view.let { recycler ->
// Some other code
LinearSnapHelper().attachToRecyclerView(recycler)   
}

实际上,您可以像这样创建自己的范围。

recycler_view.apply myCustomScope@ {
// Some other code
LinearSnapHelper().apply {
attachToRecyclerView(this@myCustomScope)
}
}

最新更新