0

I have an abstract ViewModel class,let's call it AbstractListViewModel. It has a itemsList of type MutableLiveData < List < JSONObject > >. JSONObject has 2 children : JSONChildOne and JSONChildTwo. I would like to override the property in a AbstractViewModel child to type MutableLiveData< List < JSONChildOne > >.

I tried to override in the child class to MutableLiveData < List < JSONChildOne > >

AbstractListViewModel :

abstract val itemsList : MutableLiveData<List<JSONObject>>

ChildOneListViewModel :

override val itemsList =  MutableLiveData<List<JSONChildOne>>()

Property type is "MutableLiveData < List < JSONObject > > ", which is not a subtype of overriden

  • Possible duplicate of [Is List a subclass of List? Why are Java generics not implicitly polymorphic?](https://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-are-java-generics-not-implicitly-po) – m0skit0 Oct 17 '19 at 17:52
  • Also worth reading: https://kotlinlang.org/docs/reference/generics.html – m0skit0 Oct 17 '19 at 17:53
  • Thank you but the problem is that I don't know how to use that in Kotlin – CaptainFlire Oct 17 '19 at 18:02

1 Answers1

1

You can't do that, List<Child> does not extend List<Parent> (see here for a discussion about why).

You should use a generic argument in your AbstractViewModel, for example:

abstract class AbstractViewModel<T: JSONObject> {
    abstract val itemsList : MutableLiveData<List<T>>
}

class ChildOneListViewModel : AbstractViewModel<JSONChildOne> {
    override val itemsList : MutableLiveData<List<JSONChildOne>>
}
m0skit0
  • 25,268
  • 11
  • 79
  • 127