xii
08/24/2021, 7:34 PMcorneil
08/24/2021, 8:42 PMxii
08/25/2021, 8:12 AMdata class Test(
val otherValue: Instant
val nullableMap: Map<String,String>? = null
)
class TestClass(){
fun previouslyFineFunction(foo: Test){
val body = mutableMapOf(
"otherValue" to foo.otherValue
)
if (foo.nullableMap != null){
body["baz"] = foo.nullableMap
}
}
}
body["baz"] = foo.nullableMap
worked straight upKlitos Kyriacou
08/25/2021, 8:18 AMxii
08/25/2021, 8:21 AMSmart cast to kotlin.collections.Map<kotlin.String, kotlin.String>
on the body["baz"] lineKlitos Kyriacou
08/25/2021, 8:36 AMfoo.nullableMap
to Map<kotlin.String, kotlin.String>
since it knows it's not null. But that's not where the problem is. You can't put a Map as a value into a Map that was initialized with an Instant as a value. If you really want to do that, you have to be explicit about its type when you create it:
val body : Map<String, Any> = mutableMapOf(...)
xii
08/25/2021, 8:45 AMType mismatch.
Required:
Comparable<{Instant & String}>
Found:
Map<String, String>
Type mismatch.
Required:
Serializable
Found:
Map<String, String>
Type mismatch.
Required:
{Comparable{Instant & String}> & java.io.Serializable}
Found:
Map<String, String>
Klitos Kyriacou
08/25/2021, 9:08 AMbody
depends on the contents of the MutableMap
that you initialize it with. For the compiler to give the above error message, you must have initialized it with:
val body = mutableMapOf(
"otherValue" to foo.otherValue,
"xyz" to "abc",
)
and not just with "otherValue" to foo.otherValue
. The inferred type it chooses is the most restrictive type that matches all of the arguments to mutableMapOf
. If you gave it another type, which was totally different from these two, then it would have to infer the map type as Map<String, Any>
. For example, if you did this:
val body = mutableMapOf(
"otherValue" to foo.otherValue,
"xyz" to listOf(123)
)
then your code would work.xii
08/25/2021, 9:11 AM