This Expression

To denote the current receiver, we use this expressions:

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
  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. }

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") }
  4. class A {
  5. fun printLine() { println("Member function") }
  6. fun invokePrintLine(omitThis: Boolean = false) {
  7. if (omitThis) printLine()
  8. else this.printLine()
  9. }
  10. }
  11. A().invokePrintLine() // Member function
  12. A().invokePrintLine(omitThis = true) // Top-level function
  13. //sampleEnd()
  14. }