Sobes.tech
Junior

How do the keywords 'super' and 'this' work in Kotlin?

sobes.tech AI

Answer from AI

this refers to the current instance of the class or the lambda receiver. It is used to explicitly specify a class member or a reference to the current object when ambiguity arises (for example, when a local variable has the same name).

super is used to call methods or access properties from the parent class. It is applied when you need to use the implementation of the parent class instead of the overridden implementation in the current class.

Examples:

class MyClass(val value: Int) {
    fun printValue() {
        println(this.value) // Explicit use of this to access the property
    }
}

open class Parent {
    open fun greet() {
        println("Hello from parent")
    }
}

class Child : Parent() {
    override fun greet() {
        super.greet() // Call to the parent class method
        println("Hello from child")
    }
}

When used in lambda functions, this can refer to the lambda receiver:

fun String.addExclamation(): String {
    return this + "!" // this refers to the receiver string
}

fun main() {
    val numbers = listOf(1, 2, 3)
    val sum = numbers.sum() // sum is an extension function, this inside refers to the list numbers
    println(sum)
}

To resolve ambiguity, especially when you have nested classes or lambdas with receivers, you can use qualified this (for example, this@ClassName or this@label).

class A { // implicit label @A
    inner class B { // implicit label @B
        fun Int.foo() { // implicit label @foo
            val a = this@A // reference to the A instance
            val b = this@B // reference to the B instance
            val c = this // reference to the Int receiver of the foo function
            val c1 = this@foo // reference to the Int receiver of the foo function
        }
    }
}
How do the keywords 'super' and 'this' work in… - sobes.tech