代码B来自网页,代码A将导致错误“JavaLang.Studio不能被强制转换为java. Lang.Lon”。
我试图分析原因:
首先是
key="hello"
在里面
SharedPreferences
存储字符串的值,然后我希望从同一个键中得到一个long值,当代码B试图转换时,应用程序崩溃。
我觉得代码B不好,你能修一下吗?
我猜密码
res as T
在代码B中是坏的。
代码A
val key="hello"
try {
var my1: String by PreferenceTool(this, key, "-1")
my1 = "2"
val my2: Long by PreferenceTool(this, key, -1L)
var ss=my2
}catch (e:Exception){
logError(e.message?:"None")
}
代码B
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()
}
}