This expression
When inside a class or function, we often want to refer to the enclosing instance. For example, an instance may want to invoke a method passing itself as an argument. To do this, we use the keyword this
:
class Person(name: String) { fun printMe() = println(this) }
In Kotlin terminology, the reference referred to by the this
keyword is called the current receiver. This is because it was the instance that received the invocation of the function. For example, 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, we may wish to refer to an outer instance. To do that, we must qualify the usage of this, and we do that using labels. The label we use is typically the name of the outer class, but there are more complicated rules for functions and closures discussed...