0

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 ?

stardep
  • 129
  • 1
  • 13
  • Duplicate of [this question](https://stackoverflow.com/q/71032860/10134209)? – gidds Jun 26 '23 at 18:42
  • 1
    That's a bad example of using a backing property because it accomplishes nothing. The linked question above has a similar bad example. My answer on that question has examples of two different situations where you need a backing property. – Tenfour04 Jun 26 '23 at 18:42
  • @Tenfour04 where is your answer ? – stardep Jun 27 '23 at 05:04
  • Common use case of backing property is hiding its actual (usually mutable) type like public `StateFlow` being backed by a private `MutableStateFlow`. – Pawel Jun 27 '23 at 12:01
  • https://stackoverflow.com/a/71035232/506796 – Tenfour04 Jun 27 '23 at 12:12

0 Answers0