Property Accessors trong Kotlin
🎯 Mục tiêu: Hiểu custom getters/setters và backing fields.
💡 Khái niệm
Properties trong Kotlin có thể có custom accessors.
class Rectangle(val width: Int, val height: Int) {
val area: Int
get() = width * height // Custom getter
}📝 Custom Setter
class User {
var name: String = ""
set(value) {
field = value.trim().uppercase()
}
}
fun main() {
val user = User()
user.name = " alice "
println(user.name) // ALICE
}🔧 Backing Field
var counter = 0
set(value) {
if (value >= 0) field = value // field là backing field
}🎯 Private Setter
class Account {
var balance: Double = 0.0
private set // Chỉ set từ bên trong class
fun deposit(amount: Double) {
balance += amount
}
}✅ Checklist
- Tạo custom getter
- Tạo custom setter với
field - Sử dụng private setter
Last updated on