1. Intro

In Kotlin, the “this” keyword allows us to refer to the instance of a class whose function we happen to be running. Additionally, there are other ways in which “this” expressions come in handy.

Let’s take a look.

2. Access Members of a Class With this

We can use this as a prefix for properties reference or function calls:

class Counter {
    var count = 0
 
    fun incrementCount() {
        this.count += 2
    }
}

Using this as a prefix, we can refer to the properties of the class. We can use this to resolve ambiguity with similarly named local variables.

Likewise, we can also call upon member functions using this.

3. Access Class Instance With this

We can use stand-alone this to represent an instance of the object:

class Foo {
    var count = 0

    fun incrementCount() {
        incrementFoo(this)
    }
}

private fun incrementFoo(foo: Foo) {
    foo.count += 2
}

fun main() {
    val foo = Foo()
    foo.incrementCount()
    println("Final count = ${foo.count}")
}

Here, this represents the instance of the class itself. We can pass the enclosing class instance as a parameter to a function call, for instance.

In addition, we can assign the instance to local variables using this.

4. Delegation From Secondary Constructors

In Kotlin, secondary constructors must delegate to the primary constructor. We can delegate with the use of this:

class Car(val id: String, val type: String) {
    constructor(id: String): this(id, "unknown")
}

The secondary constructor of Car delegates to the primary constructor. In fact, we can define any number of extra constructors in the class body.

However, all secondary constructors must delegate to the primary constructor or another secondary constructor using this.

5. Refer to Outer Instances With Qualified this

When used standalone, this refers to the innermost enclosing scope. But what if we want to access the instance outside that scope? We can do that by qualifying this:

class Outside {
    inner class Inside {
        fun innerInstance() = this
        fun outerInstance() = this@Outside
    }
}

Here, this refers to the inner class instance. However, to refer to the instance of the outer class, we qualify it with this@Outside. Similarly, we can refer to the outer instance from inside extension functions or function literals with receivers.

6. Conclusion

To conclude, we can use this in a variety of cases. In a nutshell, it helps us deal with ambiguity and enables us to make our code more intentional.

As always, code samples can be found over on GitHub.

Comments are closed on this article!