this 表达式
我们用 this 表示当前的接收器(receiver):
- 在类的成员中,
this指代类对象 - 在扩展函数中和普通的函数接收器中,
this指代点号左侧的接收器参数
如果 this 没有限定符,它指代最内部的封闭区域(innermost enclosing scope)。其他区域的 this 要通过标签限定符(label qualifier)来引用。
限定 this
如果要访问外部区域(类、扩展函数、带标签的函数接收器)的 this,要写成 this@label,其中 @label 表示 this 的来源。
class A { // implicit label @Ainner class B { // implicit label @Bfun Int.foo() { // implicit label @fooval a = this@A // A's thisval b = this@B // B's thisval c = this // foo()'s receiver, an Intval c1 = this@foo // foo()'s receiver, an Intval 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 receiverval d1 = this}}}}
