4

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?

1 Answers1

5

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

Josh Rosen
  • 1,686
  • 1
  • 12
  • 17
  • Making `T` a child of `Any` solved my (almost entirely unrelated) issue -- thank you! – forresthopkinsa Jan 26 '18 at 00:32
  • This results in the warning `Receiver parameter is never used`. Any idea on how to surpress/avoid that? – Anigif Sep 26 '18 at 08:38
  • @Anigif The first code block in my answer won't have this issue. The second example was an illustration of how the OP could still use the :: operator to get the class from the reified type, but in practice the first code block is probably a better choice. The behavior is slightly different, though. The first code block gets the members of the instance's runtime type, whereas the second code block gets the members of the receiver's compile-time type (e.g. a variable's declared type). – Josh Rosen Oct 02 '18 at 00:10