Kotlin compiler error: Type mismatch. Required: CapturedType(out A) Found: A

Viewed 3073

Can you explain me why I am getting this error?

interface A

open class B<T>

class Foo: A

class Item<T : A>(
    val clazz: Class<out A>,
    val b: B<out A>
)

val items = mutableListOf<Item<out A>>(
    Item(
        Foo::class.java,
        B<Foo>()
    )
)

fun <T : Any?> doSomething(
    type: Class<T>?,
    param: B<T>
) {
    // Nothing
}

fun main() {
    doSomething(items[0].clazz, items[0].b) // compiler error on 2nd argument
    // Type mismatch.
    // Required: CapturedType(out A)
    // Found: A
}

Second param in doSomething of type B<T>, so I can't understand why I am not able to pass object of type B<T>?

1 Answers

Second param in doSomething of type B<T>, so I can't understand why I am not able to pass object of type B<T>?

But items[0].b is not of type B<T>, it's of type B<out T>.

If you convert the second param of doSomething to B<out T> it will compile

Related