Search code examples
kotlinkotlinpoet

CodeBlock throwing IAE because CassName does not pass is TypeName check


I tried to initialize a property, though CodeBlock#of throws an IllegalArgumentException in CodeBlock#argToType

I looked into the root cause of the error which was at CodeBlock#argToType. Even if o is a ClassName(which also is a TypeName) it does not pass the is TypeName -> o check and throws the IllegalArguementException.

val initString = "mutableMapOf(Pair(%T, %T), Pair(%T, %T))"
val initArgs = arraysOf(...)
CodeBlock.of(initString, initArgs)

I expected the CodeBlock to be built correctly, but instead it throws the IllegalArguementException


Solution

  • I reproduced you problem and was able to fix it; I think the key question is how you pass initArgs to CodeBlock.of: this method is expecting a second varargs parameter but you're passing a single Array<...> value.

    Changing you code as follows seems to work:

    fun main(args: Array<String>) {
        val initString = "mutableMapOf(Pair(%T, %T), Pair(%T, %T))"
        val initArgs = arrayOf(String::class.java, String::class.java, String::class.java, String::class.java)
        val result = CodeBlock.of(initString, *initArgs)
        println("result is $result")
    }
    

    The key point is to pass *initArgs, and not initArgs, as second parameter of CodeBlock.of.

    I explicitly initialized initArgs' values witch type values, in order to match %T placeholder expectations.

    I hope this can help you!