Kotlin:将字符串转换为通用类型

7
我想读取输入中的一行并将其转换为通用类型。 类似以下代码:
fun <T> R() : T {
  return readLine()!!.toType(T)
}

对于R<int>(),它将调用 toInt(),对于long则调用 toLong()。如何实现这样的功能? 顺便问一下,在提供默认类型的情况下是否有可能拥有泛型类型(C++中有该功能)

1个回答

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

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

调用函数:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接