android - 不能使用类型 T 作为具体化参数,请使用类代替

标签 android generics kotlin kotlin-reified-type-parameters

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或更改 getValueinline 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/

相关文章:

c# - 我使用通用限制阻止特定类型

java - 在Java中,匿名类可以声明自己的类型参数吗?

gradle - 如何使用Kotlin DSL访问Gradle项目的插件特定属性?

intellij-idea - 使用 kotlin-stdlib 1.1.51 但加载了 kotlin-runtime 1.3

android - 如何从不同的类调用 onDraw?

android - 是否可以使用 Android DailyMotion SDK 以重复模式播放视频?

android - 保存前隐藏多个 View - Android

java - 简单的 Java 泛型应该显示编译错误,但事实并非如此

android - 半透明白色位图显示为不透明白色

android - 替换时销毁 fragment