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.
....
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. I am new to Kotlin.
CodePudding user response:
You can use let
or just give default value for extraDtls
if it is 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)