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

问题描述 投票:1回答:2

我有如下代码

        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
            }
        }

引用thisrecycler_view的语法是什么?

注意:我可以执行以下操作,但是就像想学习如何在this中拥有apply一样,它指的是Kotlin Android Extension类型类。

        recycler_view.apply {
            // Some other code
            LinearSnapHelper().apply {
                // Some other code
            }.attachToRecyclerView(this)
        }
android kotlin kotlin-android-extensions
2个回答
4
投票
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)   
}

1
投票
recycler_view.apply myCustomScope@ { // Some other code LinearSnapHelper().apply { attachToRecyclerView(this@myCustomScope) } }
© www.soinside.com 2019 - 2024. All rights reserved.