程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了kotlin 惯用的方法,在传入可为空的 mutableMap 时使其更简单大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决kotlin 惯用的方法,在传入可为空的 mutableMap 时使其更简单?

开发过程中遇到kotlin 惯用的方法,在传入可为空的 mutableMap 时使其更简单的问题如何解决?下面主要结合日常开发的经验,给出你关于kotlin 惯用的方法,在传入可为空的 mutableMap 时使其更简单的解决方法建议,希望对你解决kotlin 惯用的方法,在传入可为空的 mutableMap 时使其更简单有所启发或帮助;

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

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

解决方法

这很简单:

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

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

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

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

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

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

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

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

fun logEvent(eventName: String,String> = emptymap()) {
    service.doLogEvent(eventName,customParams + (OTHER_requIRED_KEY to OTHER_requIRED_value))
}

大佬总结

以上是大佬教程为你收集整理的kotlin 惯用的方法,在传入可为空的 mutableMap 时使其更简单全部内容,希望文章能够帮你解决kotlin 惯用的方法,在传入可为空的 mutableMap 时使其更简单所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。