KOTLIN 将字符串转换为泛型类型

Mar*_*ček 7 string generics type-conversion generic-type-argument kotlin

我想从输入中读取一行并将其转换为通用类型。就像是

fun <T> R() : T {
  return readLine()!!.toType(T)
}
Run Code Online (Sandbox Code Playgroud)

所以对于 R<int>() 它将调用 toInt() for long toLong() 等。如何实现这样的事情?顺便说一句,是否有可能有一个默认的泛型类型(C++ 有),以防万一您想提供一个

Ser*_*gey 10

您可以使用具体化类型参数编写通用内联函数:

inline fun <reified T> read() : T {
    val value: String = readLine()!!
    return when (T::class) {
        Int::class -> value.toInt() as T
        String::class -> value as T
        // add other types here if need
        else -> throw IllegalStateException("Unknown Generic Type")
    }
}
Run Code Online (Sandbox Code Playgroud)

具体化类型参数用于访问传递参数的类型。

调用函数:

val resultString = read<String>()
try {
    val resultInt = read<Int>()
} catch (e: NumberFormatException) {
    // make sure to catch NumberFormatException if value can't be cast
}
Run Code Online (Sandbox Code Playgroud)