I recently started working on Kotlin getters and setters and thereby landed on topic of Backing Properties in Kotlin. I am aware of the concept of Backing Field in Kotlin. I was refereeing to a book called Kotlin in depth by Aleksei Sedunov, in which the author says-
If you need to access a field of a property inside a class in which it's declared, you can use backing properties.
While reading the book, I came across this medium article posting the code:
class Human {
private val _age: Int = 20
val age: Int
get() {
return _age
}
val printAge = {
println("Age is: $_age")
}
}
My question is, what is actual advantage of defining a backing property where we can, rather, access the actual variable itself using this
inside the class ? Like, in the printAge
function, rather than defining the backing property and then using it, couldn't have we just done this.age ?