[Kotlin] implicit getterr && setter (field keyword)

// Shorter version
class AnotherAlternativeCustomer (val name: String,var age: Int, val address: String = "") {
    var approvered: Boolean = false
    set(value) {
        if (age>21)
            field = value
        else
            println("You cannot approve a customer under 21 years old.")
    }
}

 

c.age = 19
c.approvered = true // will print message

 

 

getter:

// Shorter version
class AnotherAlternativeCustomer (val name: String,var age: Int, val address: String = "") {
    val nextAge
    get() = age + 1
}

 

posted @ 2020-10-27 16:49  Zhentiw  阅读(101)  评论(0编辑  收藏  举报