Kotlin中的getter和setter

问题描述 投票:0回答:1

我还在这里学习吸气剂和塞特剂

Class Cat(私有名称:String){

    var sleep: Boolean = false

    fun get() = println("Function getter is called")

    fun set() = println("Function setter is called")

    fun toSleep() {
        if(sleep == true){
            println("$name, sleep!")
        }else{
            println("$name, let's play!")
        }
    }
}

fun main() {

    val gippy = Cat("Gippy")

    gippy.toSleep()
    gippy.sleep = true
    gippy.toSleep()
}

结果

Gippy, let's play!
Gippy, sleep!

预期结果应该是这样

Function getter is called
Gippy, let's play!
Function setter is called
Function getter is called
Gippy, sleep!
kotlin getter-setter
1个回答
2
投票

您未正确定义getter和setter。应该是:

var sleep: Boolean = false
    get() {
        println("Function getter is called")
        return field
    }
    set(value) {
        field = value
        println("Function setter is called")
    }

Here is more info about properties

© www.soinside.com 2019 - 2024. All rights reserved.