我想读取输入中的一行并将其转换为通用类型。
类似以下代码:
fun <T> R() : T {
return readLine()!!.toType(T)
}
对于R<int>(),它将调用 toInt(),对于long则调用 toLong()。如何实现这样的功能? 顺便问一下,在提供默认类型的情况下是否有可能拥有泛型类型(C++中有该功能)
fun <T> R() : T {
return readLine()!!.toType(T)
}
对于R<int>(),它将调用 toInt(),对于long则调用 toLong()。如何实现这样的功能? 顺便问一下,在提供默认类型的情况下是否有可能拥有泛型类型(C++中有该功能)
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
}