【发布时间】:2017-11-20 01:08:00
【问题描述】:
我有一个简单的辅助函数来从 SharedPreferences 中获取价值,如下所示:
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")
}
}
我使用了具体类型参数来切换类类型,并且由于它是一个运算符函数,我应该能够使用如下方括号语法调用:
val name: String? = prefs[Constants.PREF_NAME]
但是,每次我调用它时,都会抛出 UnsupportedOperationException 指示函数无法获取类类型。
当我附加调试器并评估 T::class 时,它给了我一个错误 "Cannot use 'T' as reified type parameter. Use a class instead."
我的功能有什么问题?我无法捕捉到错误。谁能帮忙?
编辑:整个班级是here 和this is where 我得到了错误。
更新: 似乎是 Kotlin 编译器问题。 追踪https://youtrack.jetbrains.com/issue/KT-17748 和 https://youtrack.jetbrains.com/issue/KT-17748 更新。
【问题讨论】:
-
我无法重现您的错误。我要注意的一件事是,您没有返回
when的结果,因此它将始终返回 null。 -
@JornVernee 你能看看这个吗:gist.github.com/krupalshah/782c42c70f2c58004c9bbda6291315e6我需要你的帮助。
-
如果我无法重现错误,我无法帮助您。
-
@JornVernee 我有这个活动重现了错误gist.github.com/krupalshah/fc758c054c3042d66a703cc6896d75ee
-
@JornVernee 这是它的简化版本:gist.github.com/krupalshah/d091be195999a7ddf52c3bb0f04f2bf3 我每次都得到 UnsupportedOperationException
标签: java android generics sharedpreferences kotlin