Search code examples
kotlintype-inferencetype-mismatch

kotlin - type inference and type mismatch when updating kotlin version


I'm having some difficulties trying to understand what is going on the following code:

fun helperMethodNameA(someId: String, rules: RulesObject) {
    val content = JsonNodeFactory.instance.arrayNode().apply { // A & B
        add(JsonNodeFactory.instance.objectNode().apply {
            set("body", JsonNodeFactory.instance.objectNode().apply { // C
                set("text", JsonNodeFactory.instance.objectNode().apply { // D
                    set("value", JsonNodeFactory.instance.textNode(mapper.writeValueAsString(rules))) // E
                })
            })
        })
    }
    return helperMethodNameB(someId, content.toString())
}

This project has a dependency on another which set Kotlin v1.3.20. The dependency project had the Kotlin version bumped up to v1.3.60. This bit broke with the update as per the following:

A - [ERROR] <pathToFile> [line, position] Type inference failed: inline fun <T> T.apply(block: T.() -> Unit): T
    [ERROR] cannot be applied to
    [ERROR] receiver: ArrayNode!  arguments: (ArrayNode!.() -> ArrayNode!)
B - [ERROR] <pathToFile> [line, position] Type mismatch: inferred type is ArrayNode!.() -> ArrayNode! but ArrayNode!.() -> Unit was expected
C - [ERROR] <pathToFile> [line, position] Type inference failed: Not enough information to infer parameter T in operator fun <T : JsonNode!> set(p0: String!, p1: JsonNode!): T!
    [ERROR] Please specify it explicitly.
D - [ERROR] <pathToFile> [line, position] Type inference failed: Not enough information to infer parameter T in operator fun <T : JsonNode!> set(p0: String!, p1: JsonNode!): T!
    [ERROR] Please specify it explicitly.
E - [ERROR] <pathToFile> [line, position] Type inference failed: Not enough information to infer parameter T in operator fun <T : JsonNode!> set(p0: String!, p1: JsonNode!): T!
    [ERROR] Please specify it explicitly.

What am I missing here?


Solution

  • The solution was to specify the type as bellow:

    fun helperMethodNameA(someId: String, rules: RulesObject) {
        val content = JsonNodeFactory.instance.arrayNode().apply { 
            add(JsonNodeFactory.instance.objectNode().apply {
                set<ObjectNode>("body", JsonNodeFactory.instance.objectNode().apply { 
                    set<ObjectNode>("text", JsonNodeFactory.instance.objectNode().apply { 
                        set<TextNode>("value", JsonNodeFactory.instance.textNode(mapper.writeValueAsString(rules)))
                    })
                })
            })
        }
        return helperMethodNameB(someId, content.toString())
    }