This Expression
To denote the current receiver, we use this expressions:
- In a member of a class, this refers to the current object of that class.
- In an extension function or a function literal with receiver this denotes the receiver parameter that is passed on the left-hand side of a dot.
If this has no qualifiers, it refers to the innermost enclosing scope. To refer to this in other scopes, label qualifiers are used:
Qualified this
To access this from an outer scope (a class, or extension function, or labeled function literal with receiver) we write this@label where @label is a label on the scope this is meant to be from:
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@ fun String.() {
11. val d = this // funLit's receiver
12. }
15. val funLit2 = { s: String ->
16. // foo()'s receiver, since enclosing lambda expression
17. // doesn't have any receiver
18. val d1 = this
19. }
20. }
21. }
22. }
Implicit this
When you call a member function on this, you can skip the this. part. If you have a non-member function with the same name, use this with caution, because in some cases it can be called instead:
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. }
