【问题标题】:kotlin idiomatic way to make it simpler when pass in a nullable mutableMapkotlin 惯用的方法,在传入可为空的 mutableMap 时使其更简单
【发布时间】:2021-09-23 13:23:33
【问题描述】:

从 java 转换为 kotlin

java代码

public void logEvent(String eventName, @Nullable Map<String, String> customParams) {
        if (customParams == null) {
            customParams = new HashMap<>();
        }
        customParams.put(OTHER_REQUIRED_KEY, OTHER_REQUIRED_VALUE);
        service.doLogEvent(eventName, customParams);
    }

kotlin 代码

    fun logEvent(eventName: String, customParams: Map<String, String>?) {
        var customParamsMap = HashMap<String, String>()
        if (customParams != null) {
            customParamsMap.putAll(customParams)
        }
        customParamsMap[OTHER_REQUIRED_KEY] = OTHER_REQUIRED_VALUE
        service.doLogEvent(eventName, customParamsMap)
    }

无论传入的映射是否为空,kotlin 代码都会创建临时映射。

有没有更好的方法来避免这种地图创建?

【问题讨论】:

    标签: kotlin kotlin-java-interop mutablemap


    【解决方案1】:

    这很简单:

    fun logEvent(eventName: String, customParams: MutableMap<String, String>?) {
        val customParamsMap = customParams ?: mutableMapOf()
        ...
    }
    

    或者你可以为customParams指定一个默认值:

    fun logEvent(eventName: String, customParams: MutableMap<String, String> = mutableMapOf()) {
        ...
    }
    

    请注意,在这两个示例中,我将customParams 的类型更改为MutableMap。这是 Java 代码的直接等价物。如果它需要是只读的Map,那么您实际上需要将元素复制到新地图:

    fun logEvent(eventName: String, customParams: Map<String, String>?) {
        val customParamsMap = customParams?.toMutableMap() ?: mutableMapOf()
        ...
    }
    

    【讨论】:

      【解决方案2】:

      另一个答案非常适合 Java 代码的一对一翻译。但是,如果您能够更改签名,则可以通过将参数设置为可选而不是可为空来使其在 Kotlin 中更加用户友好。

      fun logEvent(eventName: String, customParams: MutableMap<String, String> = mutableMapOf()) {
          // no need for "customParamsMap`. Use "customParams" directly.
          // ...
      }
      

      但无论哪种方式,在我看来,要求传递的地图是可变的都不是用户友好的。并且大概没有太多可能的参数,我们担心复制它们的性能。我会这样写函数,简单灵活:

      fun logEvent(eventName: String, customParams: Map<String, String> = emptyMap()) {
          service.doLogEvent(eventName, customParams + (OTHER_REQUIRED_KEY to OTHER_REQUIRED_VALUE))
      }
      

      【讨论】:

      • 谢谢。 +1,这是非常好的建议。在我的简化示例中(绝对是误导性的),只有一行可以将额外内容添加到最终地图中。在实际代码中,它有一些逻辑可以根据不同的情况构建不同的额外参数。
      猜你喜欢
      • 2014-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-16
      • 2021-04-30
      • 2011-11-29
      相关资源
      最近更新 更多