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())
r
As @karelpeeters demonstrated, the issue is that
T
is a
User
, but
User
isn't necessarily a
T
, so you can't return a list of `User`s when a list of `T`s is expected.
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.
r
You can't produce an instance of a generic type (well, you can with reflection, but that's a bad idea). Generally it's better to pass in a construction lambda.
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
?
r
As the caller is the one that specifies the type, it stands to reason that the caller should be the one that specifies how to convert the meta data to their specified type.
v
you mean smth like this?
Copy code
fun <T: User> tx(producer: () -> T): T
👌 2
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())