Kotlin – 当用返回types的函数expression时

我想利用kotlin的expression式和generics方法来简化Android的共享偏好api。

而不是一直调用getString()&getInt()等,我想要做的是创建一个扩展函数,它将根据函数的返回types进行切换,并调用适当的方法。 如下所示:

fun  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 } 

当然,这是行不通的。 但是在expression函数的返回types时有什么解决方案吗? 所有的建议都欢迎。

为了实现你想要的,你可以使用具体化的types参数 。 这将使编译器内联您的函数在它的呼叫站点与T替换为在呼叫站点使用的types。

该函数看起来像:

 @Suppress("IMPLICIT_CAST_TO_ANY") inline operator fun  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]

这些调用当然应该为编译器提供足够的types信息来推断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("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