我有如下代码
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)
}
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)
}
}