What is Property in Kotlin: Simple Explanation and Examples
property is a way to hold data inside a class using a variable with optional getter and setter methods. It combines a field and access methods into a single, easy-to-use syntax that looks like a variable but can control how data is accessed or changed.How It Works
Think of a property in Kotlin like a box that holds a value inside an object. You can open the box to see what's inside (get the value) or put something new inside (set the value). But unlike a simple box, Kotlin lets you control what happens when you open or close it by using special functions called getters and setters.
This means you can add rules, like checking if the new value is valid before storing it, or automatically updating other parts of your program when the value changes. Properties make your code cleaner because you don't have to write separate methods to get or set values; Kotlin does that for you behind the scenes.
Example
This example shows a Kotlin class with a property called name. It uses a default getter and setter to store and retrieve the value.
class Person { var name: String = "" } fun main() { val person = Person() person.name = "Alice" println(person.name) }
When to Use
Use properties whenever you want to store data inside a class and control how it is accessed or changed. They are perfect for representing characteristics of objects, like a person's name, age, or a product's price.
Properties are especially useful when you want to add validation, logging, or other actions automatically when data changes, without changing how other parts of your code use that data.
Key Points
- Properties combine a variable and its access methods into one simple syntax.
- Getters and setters can be customized to add logic when accessing or modifying data.
- Kotlin properties improve code readability and safety.