Android Studio 3.4
Kotlin 1.3.10
我有以下方法调用 findPreferences 以返回存储在共享首选项中的正确值。但是,当我使用具体化时,findPreferences 给我一个错误:无法使用类型 T 作为具体化参数。
有什么办法可以让它发挥作用吗?
fun <T: Any> getValue(key: String, defaultValue: T?): T {
return findPreferences(key, defaultValue)
}
这是根据键返回值的方法
@Suppress("unchecked_cast")
inline fun <reified T: Any> findPreferences(key: String, defaultValue: T?): T {
with(sharedPreferences) {
val result: Any = when(defaultValue) {
is Boolean -> getBoolean(key, default)
is Int -> getInt(key, defaultValue)
is Long -> getLong(key, defaultValue)
is Float -> getFloat(key, defaultValue)
is String -> getString(key, defaultValue)
else -> {
throw UnsupportedOperationException("Cannot find preference casting error")
}
}
return result as T
}
}
最佳答案
删除reified
或更改 getValue
至inline fun <reified T: Any> getValue...
.
与 reified
,我们pass a type to this function
(https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters)。 reified
要求在编译时知道类型,显然 getValue
中没有足够的类型信息。 .
关于android - 不能使用类型 T 作为具体化参数,请使用类代替,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54273316/