could someone help me understand generics in this ...
# getting-started
w
could someone help me understand generics in this situation: This works fine:
Copy code
val classes: List<KClass<*>> = listOf(
    Person::class,
    Teacher::class,
)
And this produces an error
Copy code
val classes: List<KClass<Any>> = listOf(
    Person::class,
    Teacher::class,
)
(the difference being
*
vs
Any
) I want to store any kclass, and don’t know the types. I thought
*
meant they all have the same type but i don’t know what it is
using
out Any
also seems to work
m
I would read this to understand how
*
projection works. https://typealias.com/guides/star-projections-and-how-they-work/ The entire series starting at https://typealias.com/guides/illustrated-guide-covariance-contravariance/ is very well done.
w
i actually found those articles after posting this and I am reading it now 🙂
j
KClass<Any>
is the type of the
Any
class, while
KClass<*>
represents some class, but we don't know which one. If you want to store any KClass instance, you should use the star projection
Using
KClass<out Any>
also works because it is the type of classes that are subtypes of
Any
- so basically all of them.
w
thank you. those articles actually did explain this better than i have understood it before
i’ve found the official docs to be a little confusing