用泛型处理简单SharedPreferences数据获取与存储


android中封装SharePreference可以使用这种方法。

Kotlin
import com.sun.org.apache.xpath.internal.operations.Bool
import kotlin.reflect.KFunction

object Toperator{

    /**获取泛型数据
     * @param getType 获取数据类型
     * **/
   fun getT(getType:T):T?{
        var res:T? = null
       when(getType){
           is Int ->{
                res = getType
               println("获取整形:$getType")
           }
           is String ->{
               res = getType
               println("获取字符串:$getType")
           }
           is Boolean ->{
               res = getType
               println("获取布尔:$getType")
           }
           is Double ->{
               res = getType
               println("获取双精度:$getType")
           }
           else ->{
               println("类型不匹配!")
           }

       }
        return res
   }
    /**存储泛型数据
     * @param saveT 存储数据
     * @return 链式调用**/
    fun setT(saveT:T):Toperator{
        when(saveT){
            is Int ->{
                println("存储整形:$saveT")
            }
            is String ->{
                println("存储字符串:$saveT")
            }
            is Boolean ->{
                println("存储布尔:$saveT")
            }
            else ->{
                print("数据类型不匹配!")
            }
        }
        return  Toperator
    }

}

fun main(args:Array){

   arrayOf(
           Toperator.getT("0"),
           Toperator.getT(0),
           Toperator.getT(1.0),
           Toperator.setT(arrayListOf("")))
    Toperator.setT(1111).setT("111").setT(true).setT(arrayListOf(""))

    }

null
null

null
null


文章作者: 2winter
文章链接: https://2winter.com
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 2winter !
  目录