August 2017
Intermediate to advanced
440 pages
10h
English
In the preceding example, we used a getter, so the property value is calculated each time the value is retrieved. By omitting the getter, we can create a default value for the property. This value will be computed only once during class creation and it will never change (changing the weight property will have no effect on the isHeavy property value):
class Fruit(var weight: Double) {
val isHeavy = weight > 20
}
var fruit = Fruit(7.0)
println(fruit.isHeavy) // Prints: false
fruit.weight = 30.5
println(fruit.isHeavy) // Prints: false
This type of property does have a backing field, because its value is always computed during object creation. We can also create read-write properties without a backing ...
Read now
Unlock full access