对象的getter 和 setter属性
实例
package com.tct.freeze.kotlinstudydemo
class Student {
// getter 和 setter
var name : String = "tuantuan"
// 获取属性值(name)时,先执行(field相关),再返回
get() = field.toUpperCase()// 转化为大写
var age : Int = 0
get() = field
// 设置属性值(age)时,先执行(field相关)
set(value) {
if (value < 0) {
field = 0
} else {
field = value
}
}
override fun toString(): String {
return "name is $name, age is $age"
}
}
调用实例
package com.tct.freeze.kotlinstudydemo
fun main(args : Array<String>) {
var mStudent = Student()
mStudent.name = "TuanTuan"
mStudent.age = 18
println(mStudent)
mStudent.name = "YuanYuan"
mStudent.age = -18
println(mStudent)
}
运行结果
name is TUANTUAN, age is 18
name is YUANYUAN, age is 0
Process finished with exit code 0
法迪
发布了566 篇原创文章 · 获赞 107 · 访问量 81万+
关注