Daily Kotlin - getter, setter
- normal getter, setter
코틀린은 getter와 setter를 자동 생성해주기 때문에 필요 없다.
package chap06.section1
class User(_id: Int, _name: String, _age: Int) {
val id: Int = _id
get() = field
var name: String = _name
get() = field
set(value) {
field = value
}
var age: Int = _age
get() = field
set(value) {
field = value
}
}
fun main() {
val user1 = User(1, "Kildong", 30)
user1.age = 35
println("user1.age = ${user1.age}")
}
- custom getter setter
package chap06.section1
class newUser(_id: Int, _name: String, _age: Int) {
val id: Int = _id
var name: String = _name
set(value) {
println("The name was changed")
field = value.toUpperCase()
}
var age: Int = _age
}
fun main() {
val user1 = newUser(1, "kildong", 30)
user1.name = "coco"
println("new user name = ${user1.name}")
}
The name was changed
new user name = COCO
- getter, setter 예제
나이를 속여보자. 18세 미만은 18세로. 18세 이상~30세 이하는 유지. 30세 초과는 3살 낮춰서
Comments