问题
Is it possible to have a function that returns a generic type? Something like:
fun <T> doSomething() : T {
when {
T is Boolean -> somethingThatReturnsBoolean()
T is Int -> somethingThatReturnsInt()
else -> throw Exception("Unhandled return type")
}
}
回答1:
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) { ... }
}
来源:https://stackoverflow.com/questions/43982750/a-function-with-generic-return-type