The this keyword 

The this keyword is used to refer to the object that we are currently talking about. In our current Person example, the this keyword refers to the Person object. Take a Person class example and append the this keyword with each property:

class Person(pName: String, pAge: Int, pHeight : Double ) {
var name : String
var age : Int
var height : Double
init {
this.name = pName
this.age = pAge
this.height = pHeight
}
}

The this keyword refers to the name, age, and height properties of the current object. The this keyword is optional and the main reason to use it is to remove the ambiguity between the class property and the local parameter. 

Create a simple form of the Person class with one property name and pass a constructor parameter with a similar name:

class Person(name: String) {
var name : String
init{
name = name
}
}

This situation would be confusing for the Kotlin compiler and it would throw two errors:

  • Property name must be initialized: This is the error regarding the class property
  • val cannot be reassignedThis error is within the init block

The Kotlin compiler cannot distinguish between the class property and the constructor parameter, so the this keyword plays a vital role in this situation because it refers to the current object. Adding this.name tells the compiler that the name is a class property. You must use the this keyword inside the init method to avoid the ambiguity and improve code readability:

class Person(name: String, age: Int, height : Double ) {
var name : String
var age : Int
var height : Double

init {
this.name = name
this.age = age
this.height = height
}
}

fun main(args: Array<String>) {
val abid = Person("Abid", 40, 6.0)
println("Name ${abid.name}, Age ${abid.age} Height ${abid.height}")
}

The this keyword is also used when a class contains more than one constructor, and it is required to call one constructor from within another constructor:

The output of the program doesn't change, but the this keyword increases the readability of the code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.81.33