androidgenericskotlinkotlin-reified-type-parameters

Cannot use type T as a reified parameter, use class instead


Android Studio 3.4
Kotlin 1.3.10

I have the following method that calls findPreferences to return the correct value that is stored in shared preferences. However, as I am using reified the findPreferences give me an error: Cannot use type T as a reified parameter.

Is there anyway I can get this to work?

fun <T: Any> getValue(key: String, defaultValue: T?): T {
    return findPreferences(key, defaultValue)
}

This is the method that will return the value based on the key

@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
    }
}

Solution

  • Remove reified or change getValue to inline fun <reified T: Any> getValue....

    With reified, we pass a type to this function(https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters). reified requires type to be known at compile time and obviously there is no enough type information in the getValue.