首页 > 解决方案 > 如何使`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)
        }

标签: androidkotlinkotlin-android-extensions

解决方案


在这种情况下,您可以将显式标签应用于外部 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)   
}

推荐阅读