通过泛型及reified关键字实现同一方法不同类型的返回值
如:
inline fun <reified T> Int.cast(): T {
return when (T::class) {
Int::class -> this as T
Double::class -> toDouble() as T
Float::class -> toFloat() as T
String::class -> toString() as T
else -> throw Exception("not support")
}
}
测试下方法
@Test
fun test() {
val float: Float = 12.cast()
println(float)
val double: Double = 13.cast()
println(double)
val int: Int = 14.cast()
println(int)
val string: String = 15.cast()
println(string)
}
打印结果为
12.0
13.0
14
15
网友评论