Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Override setter

Tags:

setter

kotlin

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?

like image 751
Thommy Avatar asked Aug 06 '18 10:08

Thommy


People also ask

Are getters and setters necessary in Kotlin?

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.

What is get () in Kotlin?

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.

What are Kotlin's properties?

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.

How do I add getter and setter to Kotlin?

In Kotlin, getter() and setter() methods need not be created explicitly. The Kotlin library provides both of them by default.


1 Answers

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.


like image 187
crgarridos Avatar answered Jan 01 '23 15:01

crgarridos