Home > other >  Type inference failed: Not enough information to infer parameter T
Type inference failed: Not enough information to infer parameter T

Time:05-11

I have a function that compares responses from two different endpoints. It looks like this:

suspend fun <I, T> multiplexOrShadow(
    request: I,
    v1ResponseStringGenerator: KFunction1<T, String> = ::getV1ResponseString,
    v2ResponseStringGenerator: KFunction1<T, String> = ::getV2ResponseString,
) {
 <Call two different endpoints for request>
 val v1str = v1ResponseStringGenerator(v1Response)
 val v2str = v2ResponseStringGenerator(v2Response)

 <compare v1str and v2str>
}

As you can see, the caller can pass in the function on how to generate response string from the response of the two endpoints. I also have a default function for the response generators. They look like this:

private fun <T> getV1ResponseString(v1Response: T): String {
    return v1Response.toString()
}

private fun <T> getV2ResponseString(v2Response: T): String {
    return v2Response.toString()
}

This compiles fine in IntelliJ. However, when I run the gradle build, it fails with the error

Type inference failed: Not enough information to infer parameter T in fun <T> getV1ResponseString(v1Response: T): String
Please specify it explicitly.

What am I doing wrong? I am using Kotlin 1.6.10 in my gradle build.

CodePudding user response:

Looks like this is a known issue, which is fixed since Kotlin 1.6.20: https://youtrack.jetbrains.com/issue/KT-12963.

For Kotlin 1.6.10, the workaround is to avoid using the KFunctionN types if you don't need them. For example, if you only need to invoke a function, it's fine to use just the FunctionN type, also denoted with (...) -> ...:

suspend fun <I, T> multiplexOrShadow(
    request: I,
    v1ResponseStringGenerator: (T) -> String = ::getV1ResponseString,
    v2ResponseStringGenerator: (T) -> String = ::getV2ResponseString,
) {
   ...
}
  • Related