当我想从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
答案 0 :(得分:3)
这是失败的,因为Int::class
是原始int
而T::class
是盒装类型java.lang.Integer
。它们的KClass
看起来像kotlin.Int
,因此很难区分它们。
尽管看起来有些奇怪,但这仍有效:
when (T::class) {
Int::class, Integer::class ->
}
(为了清楚起见,我将Int
留在那里,即使它永远不会触发。)