Search code examples
kotlin

Kotlin getter / setter when using a primary constructor


The example is from a Kotlin-course I'm doing:

class Car {
    var speed: Int = 0
        get() = field 
        set(value) {
            field = value
        }
}

If I like to use a primary constructor like this:

class Car(var speed: Int)

How would I have to write the getter / setter in that case?


Solution

  • You cannot write getters/setters inside of the constructor, you can do the following:

    1. Create variable inside class whose value taken from constructor.
    class Car(speed: Int) {
        var speed = speed
            get() = field 
            set(value) {
                field = value
            }
    }
    
    1. Use @JvmField annotation to restrict compiler not to auto-generate getters/setters and implement one yourself
    class Car(@JvmField private var speed: Int) {
        fun getSpeed() = speed
        fun setSpeed(value: Int) { speed = value }
    }