快速Kotlin最佳实践问题,因为我无法从文档中找到最佳方法。
假设我有以下嵌套映射(为此问题而明确指定的类型):
val userWidgetCount: Map<String, Map<String, Int>> = mapOf(
"rikbrown" to mapOf(
"widgetTypeA" to 1,
"widgetTypeB" to 2))
以下模式可以更简洁吗?
fun getUserWidgetCount(username: String, widgetType: String): Int {
return userWidgetCount[username]?.get(widgetType)?:0
}
换句话说,如果用户已知并且他们有该窗口小部件类型的条目,我想返回用户窗口小部件计数,否则为零。特别是我看到我最初可以使用[]
语法来访问地图,但在使用?.
之后,我无法在第二级看到这样做的方法。
答案 0 :(得分:5)
我会使用扩展运算符方法。
// Option 1
operator fun <K, V> Map<K, V>?.get(key: K) = this?.get(key)
// Option 2
operator fun <K, K2, V> Map<K, Map<K2, V>>.get(key1: K, key2: K2): V? = get(key1)?.get(key2)
选项1:
定义一个为可为空的地图提供get
运算符的扩展。在Kotlin的stdlib中,这种方法以Any?.toString()
扩展方法出现。
fun getUserWidgetCount(username: String, widgetType: String): Int {
return userWidgetCount[username][widgetType] ?: 0
}
选项2:
为地图地图创建特殊扩展名。在我看来,它更好,因为它显示map of maps
的合同比连续两个get
更好。
fun getUserWidgetCount(username: String, widgetType: String): Int {
return userWidgetCount[username, widgetType] ?: 0
}