Kotlin型自动拳击vs原始

时间:2018-05-10 08:24:22

标签: kotlin

class Remember private constructor() {

  private var data: ConcurrentMap<String, Any> = ConcurrentHashMap()

  private fun <T> saveValue(key: String, value: T): Remember {
    data[key] = value
    return this
  }

  private fun <T> getValue(key: String, clazz: Class<T>): T? {
    val value = data[key]
    var castedObject: T? = null


    //Failed here
    if (clazz.isInstance(value)) {
        castedObject = clazz.cast(value)
    }

    return castedObject
  }

  fun putInt(key: String, value: Int): Remember {
    return saveValue(key, value)
  }

  fun getInt(key: String, fallback: Int): Int {
    val value = getValue(key, Int::class.java)
    return value ?: fallback
  }

}

当我putInt(key, 123)时,123会自动退回到java.lang.Integer。当我从Map获得价值时,在这种情况下,如何将value键入的AnyClass<T>进行比较,其中T为Int:class.java?目前,clazz.isInstance(value)始终失败。如果这个类是用Java编写的

,它就可以工作

0 个答案:

没有答案