问题描述
从 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
的类型更改为 MutableMap
。这是 Java 代码的直接等价物。如果它需要是只读的 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))
}