Kotlin (4): Getters and Setters
Properties in Kotlin
var author: String = "Steven"
This is the same as defining the following get() and set() methods:
(example 1:)
var author: String = "Steven"
get() {
return field
}
set(value) {
field = value
}
---
(example 2:)
class Rectangle(val width: Int, val height: Int) {
val area: Int // property type is optional since it can be inferred from the getter's return type
get() = this.width * this.height
}
---
(example 3:)
var stringRepresentation: String
get() = this.toString()
set(value) {
setDataFromString(value)
}
----
Backing fields:
Every property we define is backed by a field that can only be accessed within its get() and set() methods using the special field keyword.
(example:)var counter = 0
set(value) {
if (value >= 0) field = value
}
or
var rating: Int = 5 get() { if (field < 5) { print("Warning: this is a terrible book") } return field } set(value) { field = when { value > 10 -> 10 value < 0 -> 0 else -> value } }
---
留言
張貼留言