A function with generic return type
You can use reified type to capture its class literal, like this:
inline fun <reified T> doSomething() : T {
return when (T::class.java) {
Boolean::class.java -> somethingThatReturnsBoolean() as T
Int::class.java -> somethingThatReturnsInt() as T
else -> throw Exception("Unhandled return type")
}
}
But you also must convince the compiler that T is Boolean or T is Int, as in the example, with unchecked cast.
reified
makes real T's type accessible, but works only inside inline functions. If you want a regular function, you can try:
inline fun <reified T> doSomething() : T = doSomething(T::class.java)
fun <T> doSomething(klass: Class<T>): T {
return when (klass) { ... }
}