在Kotlin中,我如何习惯性地访问可空的嵌套地图值,或者返回一个默认值?

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

换句话说,如果用户已知,并且他们有一个用于该窗口小部件类型的条目,则返回用户窗口小部件数量,否则为零。 特别是我看到我可以使用[]语法初始访问地图,但在使用?.之后,我看不到在第二级执行此操作的方法?.

我会为此使用扩展运算符方法。

 // 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的合同比两个map of maps更好。

 fun getUserWidgetCount(username: String, widgetType: String): Int { return userWidgetCount[username, widgetType] ?: 0 }