Pierre Thibault
Pierre Thibault

Reputation: 2073

How to call a method with a parameter of type Class<out T> in Kotlin?

Being:

class Test {
    fun test(c: Class<out A>) {

    }
}

open class A

class B: A()

How is it possible to call test in Testwith class B as argument?

Upvotes: 0

Views: 113

Answers (2)

Animesh Sahu
Animesh Sahu

Reputation: 8106

Like this:

val t = Test()
t.test(B::class.java)

B::class returns KClass<B>, then when you call .java it returns the java type i.e. Class<B> which is one of the type of Class<out A>.

Test and play with the code yourself.

Upvotes: 3

xegole
xegole

Reputation: 9

you could test this code for use your generic class:

fun <T : A> test(c: T) {

}

and then create the class for passing that in the parameters:

val b = B()
test(b)

Upvotes: 0

Related Questions