I have an abstract class containing the following property
var items: List<I> = listOf()
set(value) {
field = value
onDataChanged()
}
In my extending class i now want to override the setter of items
to do additional stuff before the above setter code is called. Is this possible, if yes, how?
In programming, getters are used for getting value of the property. Similarly, setters are used for setting value of the property. In Kotlin, getters and setters are optional and are auto-generated if you do not create them in your program.
In Kotlin, setter is used to set the value of any variable and getter is used to get the value. Getters and Setters are auto-generated in the code. Let's define a property 'name', in a class, 'Company'. The data type of 'name' is String and we shall initialize it with some default value.
Properties are the variables (to be more precise, member variables) that are declared inside a class but outside the method. Kotlin properties can be declared either as mutable using the “var” keyword or as immutable using the “val” keyword. By default, all properties and functions in Kotlin are public.
In Kotlin, getter() and setter() methods need not be created explicitly. The Kotlin library provides both of them by default.
You have to declare your field as open
in your parent class
open var items: List<I> = listOf()
set(value) {
field = value
onDataChanged()
}
And in your child class you override it as:
override var items: List<Int>
get() = super.items
set(value) {
super.items = value
//Your code
}
In this way, you are actually creating a property without a backing field and you are just accessing to the real parent's items
field.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With