Skip to content

Commit a5d494c

Browse files
committed
Support default value for EasyBundle.get()
1 parent cf51fc7 commit a5d494c

1 file changed

Lines changed: 18 additions & 5 deletions

File tree

utils/src/main/java/com/haoge/easyandroid/easy/EasyBundle.kt

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,13 @@ import java.lang.reflect.Type
2121
*/
2222
class EasyBundle private constructor(val bundle: Bundle){
2323

24+
/** 将map中的所有数据均存放至容器中*/
2425
fun put(map:Map<String, Any?>):EasyBundle {
2526
map.forEach { key, value -> put(key, value) }
2627
return this
2728
}
2829

30+
/** 直接一起存储不定数量的键值对数据到容器中*/
2931
fun put(vararg items:Pair<String, Any?>):EasyBundle {
3032
items.forEach { put(it.first, it.second) }
3133
return this
@@ -89,19 +91,29 @@ class EasyBundle private constructor(val bundle: Bundle){
8991
return this
9092
}
9193

94+
/** 获取指定[key]对应的值,若获取失败,则返回默认值[defValue]*/
95+
inline fun <reified T> get(key: String, defValue:T):T {
96+
return get<T>(key)?:defValue
97+
}
98+
99+
/** 获取指定[key]对应的值,可为null*/
92100
inline fun <reified T> get(key:String):T? {
93101
val type = object : TypeGeneric<T>(T::class.java){}.getType()
94102
return get(key, type) as T?
95103
}
96104

105+
/** 获取指定[key]对应的值,类型为[clazz], 若获取失败,则返回默认值[defValue]*/
106+
fun <T> get(key: String, clazz: Class<T>, defValue:T):T {
107+
return get(key, clazz)?:defValue
108+
}
109+
110+
/** 获取指定[key]对应的值,类型为[clazz], 可为null*/
97111
fun <T> get(key: String, clazz:Class<T>):T? {
98112
@Suppress("UNCHECKED_CAST")
99113
return get(key, type = clazz) as T?
100114
}
101115

102-
/**
103-
* 从容器中读取出指定[key]值,并转换为指定[type]后再返回
104-
*/
116+
/** 获取指定[key]对应的值,类型为[type], 可为null*/
105117
fun get(key:String, type:Type):Any? {
106118
val rawType = getRawClass(type)
107119
var value = bundle.get(key) ?: return returnsValue(null, rawType)
@@ -123,7 +135,8 @@ class EasyBundle private constructor(val bundle: Bundle){
123135

124136
// 处理两种情况下的数据自动转换:
125137
@Suppress("IMPLICIT_CAST_TO_ANY")
126-
val result = when(rawType.canonicalName) {
138+
return when(rawType.canonicalName) {
139+
// String自动转换基本数据类型
127140
"byte", "java.lang.Byte" -> value.toByte()
128141
"short", "java.lang.Short" -> value.toShort()
129142
"int", "java.lang.Integer" -> value.toInt()
@@ -132,11 +145,11 @@ class EasyBundle private constructor(val bundle: Bundle){
132145
"double", "java.lang.Double" -> value.toDouble()
133146
"char", "java.lang.Character" -> value.toCharArray()[0]
134147
"boolean", "java.lang.Boolean" -> value.toBoolean()
148+
// 特殊处理StringBuilder、StringBuffer
135149
"java.lang.StringBuilder" -> StringBuilder(value)
136150
"java.lang.StringBuffer" -> StringBuffer(value)
137151
else -> parseJSON(value, type)
138152
}
139-
return result
140153
}
141154

142155
private fun getRawClass(type:Type):Class<*> {

0 commit comments

Comments
 (0)