I have a simple helper function to get the value from SharedPreferences, like this:
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")
}
}
I used the reified type parameter to switch the class type, and since it is an operator function, I should be able to call the syntax with square brackets, as shown below:
val name: String? = prefs[Constants.PREF_NAME]
But every time I call it, a UnsupportedOperationException is thrown, indicating that the function cannot get the class type.
When I attach a debugger and evaluate T::class, it gives me an error"Cannot use 'T' as reified type parameter. Use a class instead."
What happened to my function? I could not catch the mistake. can anyone help?
: .
:. , Kotlin.
https://youtrack.jetbrains.com/issue/KT-17748
https://youtrack.jetbrains.com/issue/KT-17748 .