Properties
- Kotlin course
- Intermediate
- Lesson 3/116
- 5 min
Learn mutable and read-only properties.
val and var properties
In Kotlin a property holds the data of a class. A val property is read-only; it cannot change after assignment. A var property is mutable and can be reassigned.
Example: class Account(var balance: Double, val owner: String). Here balance can change, while owner is read-only. Reading or assigning a property calls a getter or setter behind the scenes. So Kotlin favors properties over separate fields and methods.
Backing field and custom getter
You can add a custom getter to give a property special behavior. Inside the getter, the field keyword accesses the underlying backing field, which avoids infinite recursion.
Example: var balance: Double = 0.0; get() = field. Here field is the property's own storage. A read-only property allows only a getter, while a mutable one allows both. Using field in a getter is the standard way to avoid calling the property itself.
Practice Define the Account class
Define a class named Account. Its primary constructor takes initial: Double. Inside the class declare var balance: Double = initial with a custom get() = field getter. Add a fun deposit(amount: Double) method whose body runs balance += amount. In main instantiate with 100.0, deposit 50.0 and print balance.
Starter code
// Define the Account class
// primary parameter initial: Double
// var balance property with custom getter
// add deposit(amount) method
// instantiate, deposit and print in mainSample solution
class Account(initial: Double) {
var balance: Double = initial
get() = field
fun deposit(amount: Double) {
balance += amount
}
}
fun main() {
val a = Account(100.0)
a.deposit(50.0)
println(a.balance)
}Expected output
150.0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which definition creates a reassignable property?
- val age: Int
- const val PI: Double
- val name = "Alex"
- var score: Int Correct answer
Explanation: A var property can be reassigned.
2 Complete the property definition
class Account {
____ balance: Double = 0.0
}
class Account {
var balance: Double = 0.0
}
Explanation: var declares a reassignable property.
3 Match the property concepts
| Term | Meaning |
|---|---|
var score: Int |
Mutable property |
val name: String |
Read-only property |
get() = field |
Custom getter |
field |
Backing field |