Properties
To write code with minimum overhead, you first have to understand the difference between fields and properties. A field is just a variable of the class that holds a value. A property of the class includes the field, getter, and setter. Since Kotlin uses the concept of properties, you should know how to access a field directly without invoking the getter or setter.
Backing properties
If you need to access a field of a property inside a class in which it's declared, you can use backing properties. If you only need to access a field from the getter or setter of its property, it's enough to use backing fields. However, if you want to access a field somewhere else, you should use backing properties. Let's look at the following example:
class Button { private var _text: String? = null var text: String set(value) { println(value) _text = value } get() { return _text + _text } fun printText() { println(_text) } }
In the preceding snippet, the _text
variable is a field...