简体   繁体   English

方法声明创建空映射时传递空值 - 输入:映射<String, String> = 界面中的 emptyMap() - Kotlin

[英]Pass null value when method declaration creates an empty map - input: Map<String, String> = emptyMap() in the interface - Kotlin

I have an interface with following declaration.我有一个带有以下声明的接口。

interface makeItHappenInterface {

   fun methodOne(params: Map<String, String> = emptyMap()):Boolean
       
}

I want to call this method but the params sometimes could be null.我想调用此方法,但params有时可能为空。

....

var extraDtls = calculate(val1, val2)

makeItHappenImpl.methodOne(extraDtls) 
// error in above line saying ----  
Type mismatch.
Required:
Map<String, String>
Found:
Map<String, String>?

so how to handle above error?那么如何处理上述错误? should I change the method declaration in interface?我应该更改接口中的方法声明吗? or any other technique to fix this properly?或任何其他技术来正确解决这个问题? I am not sure how the coding style in Kotlin.我不确定 Kotlin 的编码风格如何。 I am new to Kotlin.我是 Kotlin 的新手。

You can use let or just give default value for extraDtls if it is null .您可以使用let或只为extraDtls提供默认值(如果它是null )。

// solution 1
var extraDtls = calculate(val1, val2)
extraDtls?.let { makeItHappenImpl.methodOne(it) }

// solution 2
// using elvis operator (?:) if it is null take the right value otherwise take left value
var extraDtls = calculate(val1, val2) ?: emptyMap()
makeItHappenImpl.methodOne(extraDtls)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Kotlin:Enum类上的通用接口,具有从String映射的静态方法 - Kotlin: common interface on Enum class with static method to map from String 从 Kotlin 中的字符串 Map 获取最大值 - Get maximum value from String Map in Kotlin 为什么空字符串上的 kotlin split() 和 map(String::toInt) 得到 NumberFormatException? - Why kotlin split() and map(String::toInt) on empty string gets NumberFormatException? 如何将map一个JSON串转为Kotlin Map - How to map a JSON string to Kotlin Map 转换地图<String,List<String> &gt; 列出<Map<String,String> &gt; 在科特林 - Convert Map<String,List<String>> to List<Map<String,String>> in Kotlin kotlin.TypeCastException:null无法强制转换为非null类型kotlin.collections.Map <kotlin.String,kotlin.Any> - kotlin.TypeCastException: null cannot be cast to non-null type kotlin.collections.Map<kotlin.String, kotlin.Any> Kotlin将字符串映射到另一种类型? - Kotlin map a string to another type? Kotlin 创建列表<List<Map<String, String> &gt;&gt; - Kotlin Creating List<List<Map<String, String>>> 转换 Map<string, any> 至 Map<string, string> 在 Kotlin 中?</string,></string,> - Convert Map<String, Any> to Map<String, String> in Kotlin? Kotlin枚举用String name()声明实现Java接口 - Kotlin enum implementing a Java Interface with String name() declaration
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM