https://kotlinlang.org logo
i

Issa

03/03/2021, 10:14 AM
Morning guys, We have an interesting use case of generics in kotlin:
Copy code
import kotlin.reflect.KClass

fun main() {
    doSomething(B::class, C::class)
}

fun <T : A> doSomething(vararg dialogClasses: KClass<T>) {
    // no-op
}

open class A

class B : A()

class C : A()
the compiler complains about the second argument of
doSomething()
function even if it is a sub-type of
A
. Is there any reason for this complaint? How can this issue can be solved?
t

ti4n

03/03/2021, 10:18 AM
Copy code
fun doSomething(vararg dialogClasses: KClass<out A>) {
    // no-op
}
try this
2
i

Issa

03/03/2021, 10:28 AM
yep that worked Thanks @ti4n
a

Asagald

03/03/2021, 10:32 AM
And if you wanted to learn more about how it works (and why), you can check out this kotlin doc: https://kotlinlang.org/docs/generics.html
👌 1
w

Willy Ricardo

03/03/2021, 1:23 PM
doSomething<A>(B::class, C::class)
g

gabrielfv

03/03/2021, 9:59 PM
I think compiler/linter could infer that. Effectively
fun <T : A> doSomething(...)
is different from
fun doSomething(... KClass<out A>)
. But yeah, in this scenario it seems pretty clear @ti4n suggestion is the desired behavior