Kotlin - Class this expression

Introduction

When inside a class or function, to refer to the enclosing instance use this keyword.

For example, the following code invokes a method passing itself as an argument.

class Person(name: String) { 
     fun printMe() = println(this) 
} 

In Kotlin, the reference referred by this is called the current receiver.

If we have a string and invoke length, the string instance is the receiver.

In members of a class, this refers to the class instance.

In extension functions, this refers to the instance that the extension function was applied to.

Scope

In nested scopes, to refer to an outer instance, combine this keyword, and the labels.

The label is typically the name of the outer class.

class Building(val address: String) { 
          inner class Reception(telephone: String) { 
            fun printAddress() = println(this@Building.address) 
          } 
} 

Note the print function needed to qualify access to the Building outer instance.

Because this keyword inside the printAddress() function would have referred to the closest containing class, which is Reception.