0

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

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

4

2 回答 2

3

这很简单:

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()
    ...
}
于 2021-07-14T14:47:45.840 回答
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))
}
于 2021-07-14T14:56:00.323 回答