Android Kotlin类具体问题

时间:2017-08-20 17:28:26

标签: android kotlin

当我想从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

1 个答案:

答案 0 :(得分:3)

这是失败的,因为Int::class是原始intT::class是盒装类型java.lang.Integer。它们的KClass看起来像kotlin.Int,因此很难区分它们。

尽管看起来有些奇怪,但这仍有效:

when (T::class) {
    Int::class, Integer::class ->
}

(为了清楚起见,我将Int留在那里,即使它永远不会触发。)