kotlin类成员变量字段field的get/set

kotlin类成员变量字段field的get/set

class Person {
    var name: String = "zhangphil"
        get() = field.uppercase() //改变取出字段的
        set

    var year: Int = 2023
        get() = field
        set(value) {
            if (value < 2023) {
                field = value
            } else {
                field = -1
            }
        }

    var gender: String = "男"
        private set
}

fun main(args: Array) {
    var person = Person()
    println(person.name)

    person.year = 2024
    println(person.year)
}

 

输出:

ZHANGPHIL
-1

 

 

你可能感兴趣的:(kotlin,kotlin)