[英]Kotlin - when expression with return type of function
我希望利用kotlin的表達式和通用方法來簡化Android的共享首選項api。
而不是一直調用getString()和getInt()等,我想要做的是創建一個擴展函數,它將根據函數的返回類型進行切換並調用適當的方法。 如下所示:
fun <T> SharedPreferences.get(key: String): T? {
when (T) { //how do I switch on return type and call appropriate function?
is String -> getString(key, null)
is Int -> getInt(key, -1)
is Boolean -> getBoolean(key, false)
is Float -> getFloat(key, -1f)
is Long -> getLong(key, -1)
}
return null
}
當然,它不會起作用。 但是當表達式為函數的返回類型時,是否有任何解決方案? 歡迎所有建議。
要完全達到您的要求,您可以使用reified類型參數 。 這將使編譯器在其調用站點內聯您的函數,其中T
替換為在調用站點使用的類型。
該功能看起來像:
@Suppress("IMPLICIT_CAST_TO_ANY")
inline operator fun <reified T> SharedPreferences.get(key: String): T? =
when (T::class) {
String::class -> getString(key, null)
Int::class -> getInt(key, -1)
Boolean::class -> getBoolean(key, false)
Float::class -> getFloat(key, -1f)
Long::class -> getLong(key, -1)
else -> null
} as T?
如果你get
一個operator
函數 ,你也可以使用運算符語法調用它: prefs[name]
。
當然,調用應該為編譯器提供足夠的類型信息來推斷T
:
val i: Int? = prefs["i"] // OK, the type information is taken from the declaration
val j: Int = prefs["i"]!! // OK
val x = prefs["x"] // Error, not enough type information
val y = prefs.get<String>("y") // OK, the type will be `String?`
fun f(z: Int) = z
f(prefs["z"]!!) // OK, the type information is taken from the parameter type
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.