SharedPreferences
の小さな拡張機能を書き直したいと思います。今、それはこのようになりますKotlinでreified genericを使用する正しい方法
fun SharedPreferences.put(arg: Pair<String, Any>) {
val e = edit()
val s = arg.second
when (s) {
is Int -> e.putInt(arg.first, s)
is String -> e.putString(arg.first, s)
is Boolean -> e.putBoolean(arg.first, s)
is Long -> e.putLong(arg.first, s)
else -> throw NotImplementedError("Extension not implemented for this type")
}
e.apply()
}
はwhen
と、一般的な使用するための任意の慣用的な方法がありますか?
私の最初の推測では
inline fun <reified T> SharedPreferences.put(arg: Pair<String, T>) {
val e = edit()
when (T::class) {
Int::class -> e.putInt(arg.first, arg.second as Int)
String::class -> e.putString(arg.first, arg.second as String)
Boolean::class -> e.putBoolean(arg.first, arg.second as Boolean)
Long::class -> e.putLong(arg.first, arg.second as Long)
else -> throw NotImplementedError("Extension not implemented for this type")
}
e.apply()
}
ですが、それは
おかげのようになります。ということですが、私だから、ジェネリックスを学ぼうとしている)質問タイトルが「Reified genericを使う正しい方法」 –
@DimaRostopiraこれがあなたが探していたものなら答えを受け入れてください:) – marstran
私はジェネリックで解決を待っています、明日受け入れます良い答えがない場合は –