gpt4 book ai didi

android - Kotlin - 当表达式返回函数类型

转载 作者:IT老高 更新时间:2023-10-28 13:36:00 36 4
gpt4 key购买 nike

我想利用 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
}

当然,这是行不通的。但是有什么解决方案可以使用 when 表达式来表示函数的返回类型吗?欢迎所有建议。

最佳答案

要达到您想要的效果,您可以使用 reified type parameters .这将使编译器在其调用站点内联您的函数,并将 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 function ,您也可以使用运算符语法调用它: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

关于android - Kotlin - 当表达式返回函数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41203881/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com