August 2017
Intermediate to advanced
440 pages
10h
English
Sometimes, we want to have more control over the use of properties. We may want to perform other auxiliary operations when using a property, for example, verify a value before it's assigned to a field, log the whole operation, or invalidate an instance state. We can do this by specifying custom setters and/or getters. Let's add the ecoRating property to our Fruit class. In most cases, we would add this property to the class declaration header like this:
class Fruit(var weight: Double, val fresh: Boolean, val ecoRating: Int)
If we want to define custom getters and setters, we need to define a property in the class body instead of the class declaration header. Let's move the ecoRating property into the class body: ...
Read now
Unlock full access