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?
You cannot write getters/setters inside of the constructor, you can do the following:
class Car(speed: Int) {
var speed = speed
get() = field
set(value) {
field = value
}
}
@JvmField
annotation to restrict compiler not to auto-generate getters/setters and implement one yourselfclass Car(@JvmField private var speed: Int) {
fun getSpeed() = speed
fun setSpeed(value: Int) { speed = value }
}