Home > database >  Using Kotlin how can a base class operate on a list of base class objects, from its derived class wh
Using Kotlin how can a base class operate on a list of base class objects, from its derived class wh

Time:09-18

I have a setup vaguely like below (sorry if the Kotlin/pseudo syntax is just confusing, let me know and I'll change it).
I've got two derived classes that hold lists whose items are derived class instances. Where the list base classes have generic functionality for the lists.
I was just wondering if the way I'm doing this is silly. Is there a better way to use the derived class lists (List, List) in the base class than adding another property for the list (List) and updating it in the derived class each time changes are made to the list?
I kind of want to declare the 'items' list property in the base class A, and then override with a derived type in B and C. With the methods in class A using the list cast to the generic base class (List). But you can't do that. Cheers, hope this is of interest to someone.

class A {
    val genericItems = List<a>

    methodForGenericItems() {
        do something generic with/to the list
    }
}

class B : A {
    val items = List<b>

    updateItems() {
        update items
        genericItems = items as List<a>
    }

    methodForDerivedItems() {
        do something specific using the list
        call methodForGenericItems()
    }
}

class C : A {
    val items = List<c>

    updateItems() {
        update items
        genericItems = items as List<a>
    }

    methodForDerivedItems() {
        do something specific using the list
        call methodForGenericItems()
    }
}

class a {
    ...
}

class b : a {
    ...
}

class c : a {
    ...
}

CodePudding user response:

It really depends on whether we need to add new items in the base class (A) or not. If we need to do this then we have a problem, because A doesn't know about additional restrictions on item types introduced by B and C. Therefore, what if we use B class which works with b items, but one of functions of A adds an item of c type? We would have a list of b items, but containing c which breaks type safety. There are some solutions to this problem, depending on specific needs.

In your case it seems you only need to read/remove items in A. This is much simpler and does not require any workarounds. It is sufficient to have a regular, single property and just override its type in the subclass. But we need to inform the compiler that we won't ever add new items in A. We can do it like this:

open class A {
    open val items: MutableList<out a> = mutableListOf()
}

class B : A() {
    override val items = mutableListOf<b>()
}

out a in this code means that A can only "pull" a objects from items, but it can't "push" a objects to it.

  • Related