bkulaksiz
bkulaksiz

Reputation: 77

kotlin - Type mismatch: inferred type is MutableList<TypeA> but MutableList<InterfaceType> was expected

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

Answers (1)

Giorgio Antonioli
Giorgio Antonioli

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

Related Questions