https://kotlinlang.org logo
Title
f

felislynx

04/18/2018, 12:58 PM
Hi there, i'm trying to understand generics inside kotlin and i'm blocked. Given sample below i wanted to use in base class my FooList as param and extend this class where i'm using BarList. But i'm unable to
open class Foo {

}
class Bar:Foo(){

}
open class FooList {
	open var list:List<Foo>?=null
}
class BarList:FooList(){
	override var list:List<Bar>?=null
}
open class BaseTest {
 open var llist:List<FooList>?=null
}
class BaseTestTwo : BaseTest {
	override var llist:List<BarList>?=null
}
a

Andreas Sinz

04/18/2018, 1:00 PM
is
BaseTestTwo
failing?
f

felislynx

04/18/2018, 1:01 PM
Yes
normally in Java i would use <? extends FooList>
sorry, i've made one mistake rewriting this sample
open class FooList<T:Foo> {
    open var list: List<T>? = null
}
class BarList : FooList<Bar>() {
    override var list: List<Bar>? = null
}
a

Andreas Sinz

04/18/2018, 1:05 PM
the problem is that
list: List<T>?
is a
var
and thus is reassignable
f

felislynx

04/18/2018, 1:07 PM
ide error: var property type List<BarList> which is not a type of overriden public var list List<FooList<Foo>>
i've many times overrided default value of var or val in subclass but i didn't changed type of it during process
a

Andreas Sinz

04/18/2018, 1:09 PM
FooList<T: Foo>
is invariant, that means
FooList<Bar>
is not a subtype of
FooList<Foo>
f

felislynx

04/18/2018, 1:10 PM
is this achiveable ?
i mean what i meant, not how i did 🙂
a

Andreas Sinz

04/18/2018, 1:10 PM
if you change it to
val
and use
FooList<out T: Foo>
f

felislynx

04/18/2018, 1:13 PM
but in doing it as val, i cannot reasign it
there is no other way?
a

Andreas Sinz

04/18/2018, 1:16 PM
nope, not without losing type-safety
if you can show me more code around it, maybe we can work out a better approach
f

felislynx

04/18/2018, 1:18 PM
Foo,Bar,FooList,BarList are classes used in retrofit
BaseTest and BaseTestTwo are classes representing ViewModel
where Base is in main module, and Two i is in other flavors
a

Andreas Sinz

04/18/2018, 1:20 PM
and why do you need to reassign the list?
f

felislynx

04/18/2018, 1:21 PM
open val lists: MutableLiveData<Pair<String, ArrayList<Foo>>> = MutableLiveData()
after new network call
i have to use lists.value = Pair("Some String",response.body())