我想利用kotlin的when表达式和通用方法来简化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
}
Of Course, it will not work. But is there any solution to use when expression for return type of a function? All suggestions are welcome.