当我想从 sharedpreferences 中获取 int 值时,我得到了 UnsupportedOperationException
但我从 logcat 中显示,此类是 Int
。怎么了?
operator inline fun <reified T : Any> get(@XMLS xml: String, @KEYS key: String, defaultValue: T? = null): T {
Timber.d("${T::class} + $xml + $key + $defaultValue")
return when (T::class) {
String::class -> getShared(xml)?.getString(key, defaultValue as? String ?: "") as? T ?: "" as T
Int::class -> {
Timber.d("not triggered") //<<
getShared(xml)?.getInt(key, defaultValue as? Int ?: -1) as? T ?: -1 as T
}
Boolean::class -> getShared(xml)?.getBoolean(key, defaultValue as? Boolean == true) as? T ?: true as T
Float::class -> getShared(xml)?.getFloat(key, defaultValue as? Float ?: -1f) as? T ?: -1f as T
Long::class -> getShared(xml)?.getLong(key, defaultValue as? Long ?: -1) as? T ?: -1 as T
else -> throw UnsupportedOperationException("unknown class!")
}
}
输出:
class kotlin.Int + application_data + Ver + null
最佳答案
这是失败的,因为 Int::class
是原始 int
而 T::class
是装箱类型 java. lang.Integer
.它们的 KClass
看起来像 kotlin.Int
所以很难区分。
尽管看起来有点奇怪,但它仍然有效:
when (T::class) {
Int::class, Integer::class ->
}
(为了清楚起见,我将 Int
留在了那里,即使它永远不会触发。)
关于Android Kotlin 类具体化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45784933/