I want generic type of Any BUT NOT of type KClass<Any>

In kotlin KClass is sub class of Any… But how can I tell that I want the Object and not KClass?

For example…

public fun <T: Any> test(kclass: KClass<T>, obj: T){
    println("Hello from KClass<T>, T")
}

Clearly… we can see that function accepts class reference and object… Wrong!!!
Nothing stops you to call it like this…

test(String::class, String::class)

Ps: I’m writing library where I have overloading functions objects/classes and I need distinctions between KClass and Object class, I really really really don’t want to name the function with different names because it will burden the user with to much
names to remember…


Test you Kotlin knowledge: What will be printed on console???


fun <T: Any> test(kclass: KClass<T>, obj: T){
    println("Hello from KClass<T>, T")
}
fun <T: Any> test(obj0: T, obj1: T){
    println("Hello from T, T")
}

public fun main() {
    test(String::class, String::class)
    test("asdf", "asdf")
    test(String::class, "asdf")
    test("asdf", String::class)
}
1 Like

This is a result of T being inferred to Any. I think the nicer way to do this would be using reified type params:

public inline fun <reified T: Any> test(obj: T){
    println("Hello from KClass<T>, T")
}

and then you don’t need that distinction unless absolutely necessary. Another way would be to use the @Exact or @NoInfer internal annotations, but I wouldn’t recommend that unless you absolutely know what you’re doing

3 Likes

Dude you are my MVP! The @Exact or @NoInfer is exactly what I need! Thank you so much!!!

1 Like

FYI you can access them by copying the kotlin/internal/Annotations.kt file from stdlib into your own project, but you’ll need to add the -Xallow-kotlin-package compiler arg

2 Likes