package com.example.base.extensions

import android.content.Intent
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken


/**
 * intent 传object 数据
 */
fun Intent.putObject(any:Any) {
    this.putExtra(any::class.java.simpleName, Gson().toJson(any))
}

inline fun<reified T> Intent.getObject(): T? {
    return try {
        Gson().fromJson(this.getStringExtra(T::class.java.simpleName), T::class.java)
    } catch (e:Exception) {
        null
    }
}

/**
 * intent 传list 数据
 */
inline fun<reified T> Intent.putList(list:List<T>?) {
    this.putExtra("list${T::class.java.simpleName}", Gson().toJson(list))
}


inline fun<reified T> Intent.getList(): List<T> {
    return try {
        val str = this.getStringExtra("list${T::class.java.simpleName}")
        Gson().fromJson(str, object : TypeToken<List<T>?>() {}.type)
    } catch (e:java.lang.Exception) {
        emptyList()
    }

}