Why can't I get the class of a generic parameter?

Change your type to indicate it is not-nullable and it should work. You can do this by indicating that T needs to extend Any (rather than Any?).

fun <T : Any> test(t: T) {
    t::class
}

First, let's fix it

Make the generic type T non-nullable:

fun <T: Any> test(t: T) {
    println(t::class)
}

By default, the upper bound is Any? instead of Any:

"The default upper bound (if none specified) is Any?. Only one upper bound can be specified inside the angle brackets. If the same type parameter needs more than one upper bound, we need a separate where-clause."

Side Note: You're using !! incorrectly

"But if I change it to guaranty that t is not-null ..."

This is not what you're doing when using !!. Instead, you're telling the compiler: I don't want you to check my type for nullability. Just go ahead and call that function. I'm not afraid of NullpointerExceptions.

"In which case can t!!::class still cause trouble?"

As I said above, it causes trouble when the type, which you invoke !! on, is null. Then, same as in Java, NPEs will be thrown at runtime.


You want to use the reified type. You can learn more about the reified type parameters here or here. The code:

inline fun <reified T : Any> test(t: T) {
    println(T::class)
}