【问题标题】:How make `this` in a scope to refer to Kotlin Android Extension type class?如何使`this`在一个范围内引用 Kotlin Android Extension 类型类?
【发布时间】:2020-06-14 11:00:19
【问题描述】:

我有如下代码

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

【问题讨论】:

    标签: android kotlin kotlin-android-extensions


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您实际上可以像这样制作自己的范围。

      recycler_view.apply myCustomScope@ {
            // Some other code
            LinearSnapHelper().apply {
                attachToRecyclerView(this@myCustomScope)
            }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多