KOTLIN 将字符串转换为泛型
KOTLIN convert string to generic type
我想从输入中读取一行并将其转换为通用类型。
像
fun <T> R() : T {
return readLine()!!.toType(T)
}
所以对于 R() 它将调用 toInt() for long toLong() 等。
如何实现这样的事情?
顺便说一句,如果你想提供一个
,是否有可能有一个默认的泛型类型(C++ 有)
您可以只检查 T 类型:如果是 int - 转换为 int,如果是 long 则转换为 long。
并阅读 "out" 和 "refied" 关键字
你可以写泛型 inline function with reified type parameter:
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
}
我想从输入中读取一行并将其转换为通用类型。 像
fun <T> R() : T {
return readLine()!!.toType(T)
}
所以对于 R
您可以只检查 T 类型:如果是 int - 转换为 int,如果是 long 则转换为 long。 并阅读 "out" 和 "refied" 关键字
你可以写泛型 inline function with reified type parameter:
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
}