android - 如何使`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
}
}
引用 to 的语法是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)
}
推荐阅读
- python - 网刮美汤
- ansible - 如何在ansible中循环一系列任务
- spring-integration - 如何将请求标头添加到 outboundGateway spring integration dsl
- beacon - 如何进行 Beacon 配对蓝牙
- javascript - 如何通过控制器在模块中正确添加视图值?
- python - 每次调用 next() 时如何用 python 返回多行?
- android - 如何将位图传输到另一个活动?
- highcharts - 如何在 Highcharts 中显示表格数据中的两个特定数据点?
- c++ - C++17:元组解包时只保留一些成员
- jpa - Spring Data:何时使用 Projection 接口和 DTO 投影?