This 表达式
为了表示当前的 接收者 我们使用 this 表达式:
- 在类的成员中,this 指的是该类的当前对象。
- 在扩展函数或者带有接收者的函数字面值中, this 表示在点左侧传递的 接收者 参数。
如果 this 没有限定符,它指的是最内层的包含它的作用域。要引用其他作用域中的 this,请使用 标签限定符:
限定的 this
要访问来自外部作用域的this(一个类 或者扩展函数, 或者带标签的带有接收者的函数字面值)我们使用[[email protected]](https://www.kotlincn.net/cdn-cgi/l/email-protection),其中 @label 是一个代指 this 来源的标签:
1. class A { // 隐式标签 @A
2. inner class B { // 隐式标签 @B
3. fun Int.foo() { // 隐式标签 @foo
4. val a = [email protected] // A 的 this
5. val b = [email protected] // B 的 this
7. val c = this // foo() 的接收者,一个 Int
8. val c1 = [email protected] // foo() 的接收者,一个 Int
10. val funLit = [email protected] fun String.() {
11. val d = this // funLit 的接收者
12. }
15. val funLit2 = { s: String ->
16. // foo() 的接收者,因为它包含的 lambda 表达式
17. // 没有任何接收者
18. val d1 = this
19. }
20. }
21. }
22. }
Implicit this
当对 this 调用成员函数时,可以省略 this. 部分。 但是如果有一个同名的非成员函数时,请谨慎使用,因为在某些情况下会调用同名的非成员:
1. fun main() {
2. //sampleStart
3. fun printLine() { println("Top-level function") }
5. class A {
6. fun printLine() { println("Member function") }
8. fun invokePrintLine(omitThis: Boolean = false) {
9. if (omitThis) printLine()
10. else this.printLine()
11. }
12. }
14. A().invokePrintLine() // Member function
15. A().invokePrintLine(omitThis = true) // Top-level function
16. //sampleEnd()
17. }
