如何在内联具体化函数中 return `T` 的新实例?
How to return a new instance of `T` in an inline reified function?
我有以下代码:
private inline fun <reified T : Number> T.test(): T {
if (T::class.java == Double::class.java) {
return 0.0
}
return this
}
我预计这会起作用(只要我检查了 T
的类型),但是 IDE 指出了这一点:
The floating-point literal does not conform to the expected type T
有什么办法让它起作用吗?
您必须将其转换为 T,因为编译器不够复杂,无法识别。
private inline fun <reified T : Number> T.test(): T {
if (T::class == Double::class) {
return 0.0 as T
}
return this
}
我有以下代码:
private inline fun <reified T : Number> T.test(): T {
if (T::class.java == Double::class.java) {
return 0.0
}
return this
}
我预计这会起作用(只要我检查了 T
的类型),但是 IDE 指出了这一点:
The floating-point literal does not conform to the expected type
T
有什么办法让它起作用吗?
您必须将其转换为 T,因为编译器不够复杂,无法识别。
private inline fun <reified T : Number> T.test(): T {
if (T::class == Double::class) {
return 0.0 as T
}
return this
}