jsonkotlinserializationhashmap

Kotlin serialization of a HashMap


Got an issue with kotlin serialization where I could need some help:

import kotlinx.serialization.json.Json

fun main() {
    val someValue: Double = 1.0
    val someKey: String? = null    
        
    HashMap(readMapFromStorage()).also {
        it[someKey?:""] = someValue
    }.let {
        Json.encodeToString(it) // Cannot infer type for this parameter. Please specify it explicitly.
    }.let {
        runBlocking<Unit> { async { writeString("SomeCategory", it) } }
    }
}

private fun readMapFromStorage(): Map<String, Double> {
    return mapOf(
        "" to 1.0,
        "A" to 1.5, 
        "B" to 2.0,
    )
}

private fun writeString(key: String, value: String) {
    // do something clever
}

I receive an error in my IDE in line 10 in the call to Json.encodeToString(it):

Cannot infer type for this parameter. Please specify it explicitly.

Why is that? it is a HashMap<String, Double> here which (AFAIK) should be serializable. All tutorials I found demonstrate exactly what I tried (as far as I can tell). So why doesn't his work?


Solution

  • I suspect you miss an import for kotlinx.serialization.encodeToString. Without it we use a member function encodeToString which accepts 2 arguments, not 1 and the first argument is SerializationStrategy<T>. Extension function kotlinx.serialization.encodeToString accepts a single argument T. Still, error message is very confusing and misleading.

    Please see a working example: https://pl.kotl.in/1g4sPuGDs

    import kotlinx.coroutines.async
    import kotlinx.coroutines.runBlocking
    import kotlinx.serialization.encodeToString
    import kotlinx.serialization.json.Json
    
    fun main() {
        val someValue: Double = 1.0
        val someKey: String? = null
    
        HashMap(readMapFromStorage()).also {
            it[someKey?:""] = someValue
        }.let {
            Json.encodeToString(it) // Cannot infer type for this parameter. Please specify it explicitly.
        }.let {
            runBlocking<Unit> { async { writeString("SomeCategory", it) } }
        }
    }
    
    private fun readMapFromStorage(): Map<String, Double> {
        return mapOf(
            "" to 1.0,
            "A" to 1.5,
            "B" to 2.0,
        )
    }
    
    private fun writeString(key: String, value: String) {
        // do something clever
    }