我有以下功能:
inline fun <reified T> create(preference: Preference<T>, title: String = ""): DebugOption{
val type = when (preference) {
is Preference<String> -> Type.STRING
is Preference<Boolean> -> Type.BOOLEAN
else -> Type.STRING
}
return DebugOption(type, preference, displayTitle = StringModel(title))
}
我希望能夠輕松執行此“是”檢查,因為泛型型別已具體化,但我仍然收到編譯器錯誤:
Cannot check for instance of erased type: Preference<String>
Cannot check for instance of erased type: Preference<Boolean>
所以我很困惑我是如何濫用“具體化”的/我在這里錯過了什么。使用具體化的泛型型別作為另一個類的型別引數有問題嗎?
uj5u.com熱心網友回復:
問題是,is檢查運行時型別的preference,并且運行時型別preference,直到所有的泛型型別資訊已被洗掉不可用。畢竟,具體化的型別并不是魔法。
相反,您可以做的是檢查T,因為正如您所說,T確實是具體化的。
val type = when (T::class) {
String::class -> Type.STRING
Boolean::class -> Type.BOOLEAN
else -> Type.STRING
}
但請注意,如果Preference是協變(如List)或逆變,在某些情況下這可能無法按您的預期作業。例如:
// suppose Preference is covariant
// (i.e. the type parameter is declared <out T>)
val pref: Preference<Any> = Preference<Boolean>()
create(pref, "foo")
在這種情況下,T推斷為Any,因此type將分配Type.STRING。如果這出乎您的意料,并且您想要Type.BOOLEAN,您可能希望使用另一種方法來檢查首選項的型別,而不是具體化的型別,因為這無法在編譯時確定。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/401141.html
標籤:科特林 泛型 kotlin-reified-type-parameters
上一篇:Java中的泛型無效
