CodeBlanks Logo Icon CodeBlanks

this

Learn to access the class itself with this.

this: the current object

The this keyword refers to the current instance inside a method. When a parameter name clashes with a property name, you use this to tell them apart.

class Person(var name: String) {
    fun rename(name: String) {
        this.name = name
    }
}

this.name refers to the property, name to the parameter. The assignment copies the parameter into the property. Using this is not required when there is no clash.

When is this needed?

this is only required when a parameter clashes with a property name. If there is no clash, Kotlin finds the property automatically.

class Person(var name: String) {
    fun rename(newName: String) {
        name = newName  // no need for this
    }
}

newName does not clash with name, so this can be skipped. When there is a clash, this is mandatory; otherwise the assignment goes to the wrong place. You can still use this for clarity even without a clash.

Practice Add a set method to Person

Define class Person(var name: String); in its body add fun set(name: String) { this.name = name }. In main create val p = Person("Ayşe"), call p.set("Alex") and print p.name with println.

Starter code

Main.kt
fun main() {
    // Define a Person class with a name property and set method
    // set must use this to separate the parameter
    // Create an instance, change name with set, print
}

Sample solution

Main.kt
class Person(var name: String) {
    fun set(name: String) {
        this.name = name
    }
}

fun main() {
    val p = Person("Ayşe")
    p.set("Alex")
    println(p.name)
}

Expected output

Alex

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Fill in the blank: assign with this

Question
class Person(var name: String) {
    fun set(name: String) {
        ____.name = name
    }
}
Answer
class Person(var name: String) {
    fun set(name: String) {
        this.name = name
    }
}

Explanation: this.name refers to the property.

2 When is this used?

  • When a parameter clashes with a property name Correct answer
  • Always
  • Never
  • Only in static methods

Explanation: answer: when a parameter clashes with a property name. this separates them.

3 Match expression to meaning

Term Meaning
this.name Property access
name Parameter
this Current object
= name Assignment

All lessons in Beginner