[英]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.