A function with generic return type

我与影子孤独终老i 提交于 2020-03-16 05:20:22

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!