How to get generic parameter class in Kotlin

后端 未结 5 791
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 09:30

Firebase\'s snapshot.getValue() expects to be called as follows:

snapshot?.getValue(Person::class.java)

However I would like t

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-05 09:46

    1. Using class comparison. See https://stackoverflow.com/a/61756761/2914140.

       inline fun  SharedPreferences.getData(key: String, defValue: Any? = null): T? =
           when (T::class) {
               Integer::class -> {
                   val value = getInt(key, (defValue as? Int) ?: 0) as T
                   if (value == 0) defValue as? T else value
               }
               Long::class -> {
                   val value = getLong(key, (defValue as? Long) ?: 0L) as T
                   if (value == 0) defValue as? T else value
               }
               Boolean::class -> {
                   val value = getBoolean(key, (defValue as? Boolean) ?: false) as T
                   if (value == false) defValue as? T else value
               }
               String::class -> getString(key, defValue as? String) as T?
               else -> throw IllegalStateException("Unsupported type")
           }
      
    2. Using isAssignableFrom. See https://dev.to/cjbrooks12/kotlin-reified-generics-explained-3mie.

       inline fun  SharedPreferences.getData(key: String): T? {
           val cls = T::class.java
           return if (cls.isAssignableFrom(Integer::class.java)) {
               getInt(key, 0) as T
           } else if (cls.isAssignableFrom(Long::class.java)) {
               getLong(key, 0) as T
           } else {
               throw IllegalStateException("Unsupported type")
           }
       }
      

    For Double in SharedPreferences see https://stackoverflow.com/a/45412036/2914140.

    Use:

    val s: String? = preferences.getData("key", "")
    val i = preferences.getData("key")
    

提交回复
热议问题