Android Kotlin 类具体化问题

标签 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

最佳答案

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

尽管看起来有点奇怪,但它仍然有效:

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

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

关于Android Kotlin 类具体化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45784933/

相关文章:

android - 如何使用泛型或反射来显示/隐藏 fragment ? Kotlin 安卓

Android 按钮 setAlpha

android - 使用 facebook 的 FriendPickerFragment 查找具有相同应用程序的 friend

kotlin - 为什么此 HashMap 从无处停止工作???使用Kotlin

android - 在 Android GL 上下文重新加载时显示 ProgressDialog

android - 如何将 edittext 值存储在字符串数组中?

kotlin - 在 Kotlin 中销毁对象时未使用的参数

android - findViewById ClassCastExcpetion

android - 如何在我的 Android Activity 中使用 onItemLongClickListener?

android - 在Android中绘制圆角矩形