Qualified ‘this’ in Kotlin

The only thing we learnt about this pointer in other languages is “this is an implicit pointer which points to the calling object”. As clear from the definition, it points to the object which calls the respective function or property.

This post was originally posted at https://agrawalsuneet.github.io/blogs/qualified-this-in-kotlin/ and reposted on Medium on 7th Feb 2019.
//java code
//extending Android View class
public class CustomView extends View {

public CustomView(Context context) {
super(context);

getViewTreeObserver()
.addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout() {
//this.
//will not get the reference of
//CustomView here
}
});
}
}
//java code
//extending Android View class
public class CustomView extends View {

public CustomView(Context context) {
super(context);

final CustomView view = this;

getViewTreeObserver()
.addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout() {
view.doSomething();
}
});
}

private void doSomething(){

}
}
class CustomView : View {

constructor(context: Context) : super(context) {

viewTreeObserver
.addOnGlobalLayoutListener (
object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
this@CustomView.doSomething()
}
})
}

private fun doSomething() {
}
}
class CustomView : View {

constructor(context: Context) : super(context) {

viewTreeObserver
.addOnGlobalLayoutListener {
this@CustomView.doSomething()
}
}

private fun doSomething() {
}
}
class OuterClass {

inner class InnerClass{

fun Int.intExtensionFunction(){

val outerThis = this@OuterClass
val innerThis = this@InnerClass
val intExtThis = this@intExtensionFunction

val currentThis = this
// int receiver, which will be an int

val funLiteral = lambda@ fun String.() {
val funLiteralThis = this
// funLiteral's receiver which will be a string
}


val funLiteral2 = { string: String ->
val funLiteral2This = this
//since this lambada doesn't have any receiver,
//this will be an int (the extension fun reference)
}

}
}
}
  • In an extension function or a function literal with the 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.
  • No need to define any final object to use any this reference.