首页 > 解决方案 > kotlin 惯用的方法,在传入可为空的 mutableMap 时使其更简单

问题描述

从 java 转换为 kotlin

爪哇代码

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);
    }

科特林代码

    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 代码都会创建临时地图。

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

标签: kotlinkotlin-java-interopmutablemap

解决方案


这很简单:

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

或者,您可以为 指定默认值customParams

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

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

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

推荐阅读