具有泛型返回类型的函数

时间:2017-05-15 15:00:42

标签: generics kotlin

是否可以使用返回泛型类型的函数?类似的东西:

fun <T> doSomething() : T {
    when {
        T is Boolean -> somethingThatReturnsBoolean()
        T is Int -> somethingThatReturnsInt()
        else -> throw Exception("Unhandled return type")
    }
}

3 个答案:

答案 0 :(得分:7)

您可以使用reified类型来捕获其类文字,如下所示:

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")
    }
}

但是你也必须说服编译器T是布尔值,或者T是Int,如例子所示,使用未经检查的强制转换。

reified使真正的T类型可访问,但仅适用于内联函数。如果您想要常规功能,可以尝试:

inline fun <reified T> doSomething() : T = doSomething(T::class.java)
fun <T> doSomething(klass: Class<T>): T {
    return when (klass) { ... }
}

答案 1 :(得分:0)

Any可能是您要使用的东西。这是Kotlin类层次结构的根。

对于语法为Any?的Any,也可以选择使用

fun doSomething(key: Any): Any {
    when {
             key is Boolean -> return true
             key is Int -> return 1
             else -> throw Exception("Unhandled return type")
         }
}

答案 2 :(得分:0)

您也可以直接将 somethingThatReturnsInt() 等函数传递给泛型函数,并从传递的函数本身推断返回类型。以下是 Kotlin 的示例:

// This function takes any method you provide and infers the result-type
public fun<T> generic_function(passed_function: () -> T): T? =
    passed_function()


// Pass your function. The return type will be inferred directly from somethingThatReturnsInt()'s return-type
val res: Int? = generic_function(::somethingThatReturnsInt)

// For the sake of completeness, this is valid as well
val res: Int? = generic_function<Int?> { somethingThatReturnsInt() }

这样您就不必处理 when-scenarios 并且您的返回类型是通用的,具体取决于传递的函数。