Kotlin KClass instance inside extension function

I need to access to class type inside a generic extension function. For example, if I want to make an extension function to return a collections of the members of the type I am extending, I would do:

fun <T> T.getMembers() =
       this::class.memberProperties

The problem is that I cannot do this::class nor T::class inside the function. Is there any way to access to the class type of a generic type?

Upvotes: 4

Views: 2831

Answers (1)

Josh Rosen
Josh Rosen

Reputation: 1686

In general, you wouldn't use :: to get the class from this, because this references an instance, not a type. Generally you would get the class from this with this.javaClass.kotlin

T references a type, so generally you would reference the KClass with T::class.

However, in your specific code snippet neither of these will work without some additional changes.

Since generic type T is not constrained to Any, you cannot access the javaClass field. To add the constrain, use:

fun <T : Any> T.getMembers() =
   this::class.memberProperties

Since generic type is not reified, you cannot use T::class. To reify T, use:

inline fun <reified T : Any> T.getMembers() =
   T::class.memberProperties

See https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters

Upvotes: 5

Related Questions