Android Kotlin-返回函数类型的when表达式
我想利用kotlin的when表达式和通用方法来简化Android的共享首选项api 我要做的不是一直调用getString()&getInt()等,而是创建一个扩展函数,该函数将根据函数的返回类型进行切换,并调用适当的方法。如下所示:Android Kotlin-返回函数类型的when表达式,android,function,generics,types,kotlin,Android,Function,Generics,Types,Kotlin,我想利用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 f
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
}
fun sharedreferences.get(key:String):T?{
当(T){//我如何打开返回类型并调用适当的函数?
is String->getString(键,null)
is Int->getInt(键-1)
is Boolean->getBoolean(键,false)
is Float->getFloat(键,-1f)
is Long->getLong(键,-1)
}
返回空
}
当然,这是行不通的。但对于函数的返回类型,有什么解决方案可以使用when表达式吗?欢迎提出所有建议。要实现您想要的目标,您可以使用。这将使编译器在其调用位置内联函数,并用调用位置使用的类型替换
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?
有趣…谢谢。但是“这将使编译器内联您的函数”。你能解释一下内联实际上做什么吗。我阅读了文档,但它显示内联与一些不同的东西相关联,比如。我不是专家。你能简单地解释一下内联实际上做了什么吗?@KrupalShah,在Kotlin中,实际上并不打算成为一个性能工具,因为JVM本身在运行时对内联函数的管理已经足够好了。相反,
inline
函数用于灵活性。两个主要用例是and(break
和continue
可能会在将来添加到return
。@KrupalShah,请注意,这两个用例都需要转换函数体(对于具体化的泛型,类型参数将替换为调用站点中存在的类型,因为否则类型参数将为,并且代码无法使用它;对于控制流,函数参数是内联的,因此内部的return
将与外部函数一起工作)。这些转换是为每个函数调用完成的,然后转换后的代码在调用站点内联。这是一个很好的解决方案,但最好只在内联函数中获取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