Kotlin 中的 getter 和 setter

getter and setter in Kotlin

我还在学习getter和setter。如果我在 getter 和 setter 中使用字段,它仍然不起作用:

class Cat(private val name: String) {

    var sleep: Boolean = false

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

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

    fun toSleep() {
        if (sleep) {
            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!

您错误地定义了 getter 和 setter。应该是:

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

其中 field - 是 Backing Field。来自文档:

Fields cannot be declared directly in Kotlin classes. However, when a property needs a backing field, Kotlin provides it automatically. This backing field can be referenced in the accessors using the field identifier.

Here is more info about getters and setters.