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
}
1条答案
按热度按时间vvppvyoh1#
可以用具体化的类型参数编写泛型inline function:
具体化类型参数用于访问传递参数的类型。
调用函数: