kotlin - 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 代码都会创建临时地图。
有没有更好的方法来避免创建此地图?
解决方案
这很简单:
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()
...
}
推荐阅读
- python - ModuleNotFoundError:没有名为“mysite.apps”的模块
- python - 自定义 JSON 编码器引发“对象不可序列化 JSON”错误
- sql - 有没有办法改进这个查询
- python - 使用假设库创建多索引 pd.DataFrame
- bash - 使用 for 循环在 bash 中启动多个进程
- angular - 如何使用父类输入属性创建动态组件
- sql - 创建和插入具有多对多关系的数据
- c# - 如何从 GitHub 找到下载的 onlineShop-master.zip 文件的 URL
- java - 尝试连接到 Kuzzle 服务器时 SSL 握手中止
- computer-vision - 在 YOLACT/YOLACT++ 中只预测一个班级(人)