不能将类型 T 用作具体化参数,请改用 class

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

Android Studio 3.4
Kotlin 1.3.10

我有以下调用 findPreferences 的方法 return 存储在共享首选项中的正确值。但是,当我使用具体化时,findPreferences 给我一个错误:无法将类型 T 用作具体化参数。

无论如何我可以让它工作吗?

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

这是将 return 基于键

的值的方法
@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.

中没有足够的类型信息