This 表达式

为了记录下当前接受者,我们使用 this 表达式:

在类的成员中,this 表示当前类的对象

在扩展函数或扩展字面函数中,this 表示 . 左边接收者参数

如果 this 没有应用者,则指向的是最内层的闭合范围。为了在其它范围中返回 this ,需要使用标签

this使用范围

为了在范围外部(一个类,或者表达式函数,或者带标签的扩展字面函数)访问 this ,我们需要在使用 this@lable 作为 lable

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

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

10. val funLit = @lambda {String.() ->
11. val d = this // funLit's receiver
12. val d1 = this@lambda // funLit's receiver
13. }

16. val funLit2 = { (s: String) ->
17. // foo()'s receiver, since enclosing function literal
18. // doesn't have any receiver
19. val d1 = this
20. }
21. }
22. }
23. }