【发布时间】:2019-08-08 03:14:41
【问题描述】:
代码 A 在我的旧版本中运行良好,现在我将我的 Android Studio 更新到 3.4.2,并 buildToolsVersion "29.0.1",并使用最新的 androidx。
但我收到错误类型不匹配,您可以看到图 1,我该如何解决?谢谢!
图片 1
代码 A
class PreferenceTool<T>(private val context: Context, private val name: String, private val default: T) {
private val prefs: SharedPreferences by lazy {
context.defaultSharedPreferences
}
operator fun getValue(thisRef: Any?, property: KProperty<*>): T = findPreference(name, default)
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
putPreference(name, value)
}
@Suppress("UNCHECKED_CAST")
private fun findPreference(name: String, default: T): T = with(prefs) {
val res: Any = when (default) {
is Long -> getLong(name, default)
is String -> getString(name, default)
is Int -> getInt(name, default)
is Boolean -> getBoolean(name, default)
is Float -> getFloat(name, default)
else -> throw IllegalArgumentException("This type can be saved into Preferences")
}
res as T
}
@SuppressLint("CommitPrefEdits")
private fun putPreference(name: String, value: T) = with(prefs.edit()) {
when (value) {
is Long -> putLong(name, value)
is String -> putString(name, value)
is Int -> putInt(name, value)
is Boolean -> putBoolean(name, value)
is Float -> putFloat(name, value)
else -> throw IllegalArgumentException("This type can't be saved into Preferences")
}.apply()
}
}
添加内容 1
此外,我发现代码 B 和代码 C 都可以正确编译。我不知道为什么。似乎is String -> getString(name, default) 导致错误。
代码 B
@Suppress("UNCHECKED_CAST")
private fun findPreference(name: String, default: T): T = with(prefs) {
val res: Any = when (default) {
is Long -> getLong(name, default)
else -> throw IllegalArgumentException("This type can be saved into Preferences")
}
res as T
}
代码 C
@Suppress("UNCHECKED_CAST")
private fun findPreference(name: String, default: T): T = with(prefs) {
val res: Any = when (default) {
is Long -> getLong(name, default)
is Int -> getInt(name, default)
is Boolean -> getBoolean(name, default)
is Float -> getFloat(name, default)
else -> throw IllegalArgumentException("This type can be saved into Preferences")
}
res as T
}
添加内容 2
prefs.getString(name, default) 似乎由 Image 2 返回 String?。不知道Build 29.0.1有没有bug?
图片 2
【问题讨论】:
标签: android android-studio kotlin androidx