Reputation: 77
I'm trying to code some stuff in kotlin but I have some problem with that. How can i achieve this problem? I share my code.. Please help me!
interface InterfaceType {}
open class ConcreteImpl: InterfaceType {}
class TypeA: ConcreteImpl() {}
fun test() {
var interfaceTypeList: MutableList<InterfaceType> = mutableListOf()
var typeAList: MutableList<TypeA> = mutableListOf()
interfaceTypeList = typeAList
}
You can show the code from here.
Upvotes: 0
Views: 3040
Reputation: 16224
This is related to Kotlin types variance
.
The type MutableList<T>
is invariant in its type T
so you can't assign a MutableList<InterfaceType>
to a MutableList<TypeA>
.
To be able to assign it, since InterfaceType
is a supertype of TypeA
, you'd need instead a class covariant in its type (e.g. List
).
interface InterfaceType {}
open class ConcreteImpl: InterfaceType {}
class TypeA: ConcreteImpl() {}
fun test() {
var interfaceTypeList: List<InterfaceType> = mutableListOf()
var typeAList: MutableList<TypeA> = mutableListOf()
interfaceTypeList = typeAList
}
Otherwise you should make an unchecked cast to MutableList<InterfaceType>
.
```kotlin
interface InterfaceType {}
open class ConcreteImpl: InterfaceType {}
class TypeA: ConcreteImpl() {}
fun test() {
var interfaceTypeList: MutableList<InterfaceType> = mutableListOf()
var typeAList: MutableList<TypeA> = mutableListOf()
// Unchecked cast.
interfaceTypeList = typeAList as MutableList<InterfaceType>
}
Upvotes: 4