Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get KClass of generic classes like BaseResponse<Iterable<User>>

Tags:

kotlin

If I try to get

BaseResponse<Iterable<User>>::class

I get error error only classes are allowed on the left hand side of class literal. I have searched and still not found how to get generic classes's type in kotlin.

like image 332
dtunctuncer Avatar asked Jan 28 '23 15:01

dtunctuncer


1 Answers

You can't -KClass can only describe the class BaseResponse, and you can get a KClass instance that does that with BaseResponse::class.

What you have however, BaseResponse<Iterable<User>>, is a concrete type, which you can be represented as a KType instance. KType instances can be created, for example, with the createType function. This would look something like this:

// User
val userType = User::class.createType()
// Iterable<User>
val iterableOfUserType = Iterable::class.createType(arguments = listOf(KTypeProjection.invariant(userType)))    
// BaseResponse<Iterable<User>>
val responseType = BaseResponse::class.createType(arguments = listOf(KTypeProjection.invariant(iterableOfUserType)))

I made the choice of making the type parameters both invariant, there's also factory methods in KTypeProjection to create covariant or contravariant types, as you need them.

like image 185
zsmb13 Avatar answered Jan 31 '23 11:01

zsmb13