this 表达式

我们用 this 表示当前的接收器(receiver):

  • 在类的成员中,this 指代类对象
  • 在扩展函数中和普通的函数接收器中,this 指代点号左侧的接收器参数

如果 this 没有限定符,它指代最内部的封闭区域(innermost enclosing scope)。其他区域的 this 要通过标签限定符(label qualifier)来引用。

限定 this

如果要访问外部区域(类、扩展函数、带标签的函数接收器)的 this,要写成 this@label,其中 @label 表示 this 的来源。

  1. class A { // implicit label @A
  2. inner class B { // implicit label @B
  3. fun Int.foo() { // implicit label @foo
  4. val a = this@A // A's this
  5. val b = this@B // B's this
  6. val c = this // foo()'s receiver, an Int
  7. val c1 = this@foo // foo()'s receiver, an Int
  8. val funLit = lambda@ fun String.() {
  9. val d = this // funLit's receiver
  10. }
  11. val funLit2 = { s: string ->
  12. // foo()'s receiver, since enclosing lambda expression
  13. // doesn't have any receiver
  14. val d1 = this
  15. }
  16. }
  17. }
  18. }