chomsky_dazai
chomsky_dazai

Reputation: 29

getter and setter in Kotlin

I am still learning about getter and setter here. If I used field in getter and setter It still not working:

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()
}

The results:

Gippy, let's play!
Gippy, sleep!

Expecting result supposed to be like this:

Function getter is called
Gippy, let's play!
Function setter is called
Function getter is called
Gippy, sleep!

Upvotes: 2

Views: 1657

Answers (1)

Sergio
Sergio

Reputation: 30605

You defined getter and setter incorrectly. It should be:

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

where field - is a Backing Field. From the docs:

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.

Upvotes: 4

Related Questions