如何使范围内的 `this` 引用 Kotlin Android 扩展类型 class?
How make `this` in a scope to refer to Kotlin Android Extension type class?
我有如下代码
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
的语法是什么?
注意:我可以做下面的,但就像学习如何拥有我们如何拥有 apply
中的 this
指的是 Kotlin Android 扩展类型 class.
recycler_view.apply {
// Some other code
LinearSnapHelper().apply {
// Some other code
}.attachToRecyclerView(this)
}
实际上你可以像这样制作你自己的示波器。
recycler_view.apply myCustomScope@ {
// Some other code
LinearSnapHelper().apply {
attachToRecyclerView(this@myCustomScope)
}
}
在这种情况下,您可以将显式标签应用于外部 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 {
// 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
的语法是什么?
注意:我可以做下面的,但就像学习如何拥有我们如何拥有 apply
中的 this
指的是 Kotlin Android 扩展类型 class.
recycler_view.apply {
// Some other code
LinearSnapHelper().apply {
// Some other code
}.attachToRecyclerView(this)
}
实际上你可以像这样制作你自己的示波器。
recycler_view.apply myCustomScope@ {
// Some other code
LinearSnapHelper().apply {
attachToRecyclerView(this@myCustomScope)
}
}
在这种情况下,您可以将显式标签应用于外部 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)
}