Qualified ‘this’ in Kotlin

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 a member of a Class, this refers to the current object of that class.
  • 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.

--

--

https://agrawalsuneet.github.io/

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store