我有一個簡單的輔助函數從SharedPreferences得到的值是這樣的:Kotlin - 不能使用'T'作爲實體類型參數。使用一個類,而不是
operator inline fun <reified T : Any> SharedPreferences.get(key: String, defaultValue: T? = null): T? {
return when (T::class) {
String::class -> getString(key, defaultValue as? String) as T?
Int::class -> getInt(key, defaultValue as? Int ?: -1) as T?
Boolean::class -> getBoolean(key, defaultValue as? Boolean ?: false) as T?
Float::class -> getFloat(key, defaultValue as? Float ?: -1f) as T?
Long::class -> getLong(key, defaultValue as? Long ?: -1) as T?
else -> throw UnsupportedOperationException("Not yet implemented")
}
}
我已經用具體化類型參數有切換是類類型,因爲它是一個運營商的功能,我應該是能夠用方括號語法來調用象下面這樣:
val name: String? = prefs[Constants.PREF_NAME]
但是,我每次調用它,UnsupportedOperationException異常被拋出指示功能是不是能夠得到類類型。
當我連接調試和評估T::class
,這是給我一個錯誤"Cannot use 'T' as reified type parameter. Use a class instead."
這有什麼錯我的功能?我無法理解這個錯誤。誰能幫忙?
編輯:整個班級是here和this is where我得到的錯誤。
更新:這似乎是Kotlin編譯器問題。 跟蹤https://youtrack.jetbrains.com/issue/KT-17748和 https://youtrack.jetbrains.com/issue/KT-17748更新。
我無法重現你的錯誤。我可以注意到的一件事是你沒有返回'when'的結果,所以它總是會返回null。 –
@JornVernee你能看到這個:https://gist.github.com/krupalshah/782c42c70f2c58004c9bbda6291315e6我需要你的幫助。 –
如果我無法重現錯誤,我無法幫助您。 –