美文网首页
Kotlin编码窍门之this表达式(This Expressi

Kotlin编码窍门之this表达式(This Expressi

作者: 已迁至知乎_此不再维护 | 来源:发表于2017-06-03 11:04 被阅读0次

为了表示当前接收者,我们使用this表达式:

  1. 在类的成员中,this指的是当前类的对象
  2. 在扩展函数或具有接收者的函数字面值,this指的是.操作符左侧的接收者参数

如果this没有修饰符,它归属于最内层封闭作用域。为了让this归属于其他作用域,可以使用标签修饰符:

被修饰的this(Qualified this)

为了在外部作用域(类,扩展函数,或被标签的带有接收者的字面函数)访问this,我们使用this@label@label是一个代指this来源的标签:

class A { // implicit label @A
    inner class B { // implicit label @B
        fun Int.foo() { // implicit label @foo
            val a = this@A // A's this
            val b = this@B // B's this

            val c = this // foo()'s receiver, an Int
            val c1 = this@foo // foo()'s receiver, an Int

            val funLit = lambda@ fun String.() {
                val d = this // funLit's receiver
            }


            val funLit2 = { s: String ->
                // foo()'s receiver, since enclosing lambda expression
                // doesn't have any receiver
                val d1 = this
            }
        }
    }
}

相关文章

网友评论

      本文标题:Kotlin编码窍门之this表达式(This Expressi

      本文链接:https://www.haomeiwen.com/subject/wmipfxtx.html