Dynamic cast in Kotlin

Try to change your code to

fun <T: Any> cast(any: Any, clazz: KClass<out T>): T = clazz.javaObjectType.cast(any) 

Explanation

Because the type of the parameter any is Any, it's always a reference type and primitives will be boxed. For the second parameter, it seems that Kotlin reflection will prefer primitive types to reference types, which is why Int::class.java will default to ìnt, not Integer. By using javaObjectType we force the usage of the boxed reference type.

Alternative

You could also use the following function definition:

inline fun <reified T: Any> cast(any: Any): T = T::class.javaObjectType.cast(any) 

// usage

cast<Int>(0)

Kirill Rakhman 's answer works well for non-nullable type. But we cannot have T::class if T is nullable. So I suggest the following to deal with nullable type.

inline fun <reified T> cast(any: Any?): T = any as T

Usage

val l32: Number = cast(32L)
val ln1: Number? = cast(null) // works
val ln2: Number = cast(null) // fails at runtime