4

I try to use the next method:

fun <T> put(value: T){
    val clazz = T::class.java
}

but has exception Kotlin: Only classes are allowed on the left hand side of a class literal

How obtain class from generic param?

What are other options except class can be passed as param?

Istvan Nagy
  • 310
  • 4
  • 13
Alex Klimashevsky
  • 2,457
  • 3
  • 26
  • 58

2 Answers2

6

To access generic types within a function you need to make the types reified. Since this is not natively supported by the JVM its only available in inlined functions:

inline fun <reified T : Any> put(value: T) {
    val clazz = T::class.java
}

The type bound of Any is required to prevent some complications with nullable types.

Jayson Minard
  • 84,842
  • 38
  • 184
  • 227
Kiskae
  • 24,655
  • 2
  • 77
  • 74
  • what are restriction for using this method from Java code? – Alex Klimashevsky Mar 11 '16 at 15:06
  • @AlexKlimashevsky you can search for the 1000 examples of TypeReference, TypeToken, TypeRef and so on that do this similar type of thing from a Java viewpoint, you'll need to follow those patterns as Kotlin can make Kotlin nicer, but not make Java nicer. – Jayson Minard Mar 12 '16 at 00:21
0

fixed by

fun <T: Any> put(value: T){
    val clazz = value.javaClass
}
Alex Klimashevsky
  • 2,457
  • 3
  • 26
  • 58
  • 3
    This may fail sometimes: consider `put(0 as Number)`, here `T` is `Number`, but `value.javaClass` will be `Integer`. If this is not what you want, use reified generics as stated in the other answer. – hotkey Mar 11 '16 at 15:26
  • @hotkey I think more about Java compatibility. so this is what I want now – Alex Klimashevsky Mar 11 '16 at 15:42
  • In that case you might as well make `clazz` the parameter. – Kirill Rakhman Mar 11 '16 at 16:32
  • @AlexKlimashevsky you should make it clear in your question that you want the class of `value` and not of the generic type parameter, because your comments are to the contrary of what you originally stated. And @hotkey is correct, you will get a wrong answer for the generic parameter, but a correct answer for the class of the parameter passed to the function. – Jayson Minard Mar 12 '16 at 00:18