2
votes

I would like to find a way to generate getters and setters of some Kotlin property automatically. In java there is no problem to do it.

I am working with data binding and I have many classes which looks like so:

class AnimalListItemPresenter(private var _animal: String) : BaseObservable() {
    var animal: String
        @Bindable get() = _animal
        set(value) {
            _animal = value
            notifyPropertyChanged(BR.item)
        }

}

I know that it is not possible not possible to generate the logic in setter but can I at leat somehow generate the standard getter and setter?

1
use data class! - Dennis Vash
There is no "standard getter and setter" in Kotlin. Or, rather, they are built into the language. Your get() and set() are overriding the "standard getter and setter". - CommonsWare
In Kotlin, fields are already translated into standard getters and setters. Why not just add your custom setter to the constructor field? - TheWanderer

1 Answers

5
votes

Standard getters and setters are built into Kotlin.

example:

class Customer {
  var id = "",
  var name = ""
}

and you can use it like:

fun copyCustomer(customer: Customer) : Customer {
    val result = Customer() 
    result.name = customer.name 
    .
    .
    return result
}

You can also override the default getter and setter in the manner you have done in the code snippet. Good Resource: https://kotlinlang.org/docs/reference/properties.html

If you want a quick way of generating boilerplate code in Android Studio -> Alt + Enteron the property and you canAdd GetterorAdd Setter` among different options

enter image description here