我有如下代码
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
的语法是什么?注意:我可以执行以下操作,但是就像学习如何在
this
中拥有apply
一样,它指的是Kotlin Android Extension类型类。 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)
}
关于android - 如何在范围内使 `this`引用Kotlin Android Extension类型类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62371582/