dumb question about generics - what is wrong? ``` ...
# getting-started
v
dumb question about generics - what is wrong?
Copy code
fun <T : User>gen(): List<T> = listOf(User())
k
Yeah with generics I often get stuck in in abstract explanations myself.
v
Thanks, i'm just starting getting all this covariance thing
So, there is no way to produce subtypes of generic parameter?
k
Well sometimes, depends on the situation. The stdlib
emptyList
has the same signature as your function, but there it is correct.
v
well, you can with reflection
actually that's the thing in my case so the method always returns instances of passed type
k
How do you know the type then? You could have a signature like this:
fun <T: User> gen(cls: KClass<T>): List<T>
, I think that has the potential to be correct.
v
yep sorry, oversimplified the example
there is an argument which contains all necessary meta info (including class)
k
Can't you give that object a generic parameter similar to
KClass
?
v
you mean smth like this?
Copy code
fun <T: User> tx(producer: () -> T): T
👌 1
m
@vlad.minaev i think here is what you are seeking for . creating instance of generic type using reified.
Copy code
inline fun < reified  T : User>gen(): List<T> = listOf(T::class.java.newInstance())