Reputation: 257
Let's say i have classes A as am abstract parent class while B & C extends it. I wanna create a function with an option to input classes B & C, like the childs of A (or A itself)
In java I would just have to define a type as Class<? : Extends A>
In Kotlin I can do KClass<*>
, but it seems like too much freedom.
How can I limit the options only for the childs of A?
Upvotes: 2
Views: 1745
Reputation: 153
In Kotlin if you KClass<*>
will accept all the classes. If you define with KClass<A>
will accept only A
class. In order to accept A and its children, you have defined KClass<out A>
. See the example below
abstract class A
class B:A()
class C:A()
fun method (param : KClass<out A>){}
method(B::class)
Upvotes: 8