0

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

Zctrap
  • 15
  • 5

1 Answers1

1

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!

Pietro Martinelli
  • 1,776
  • 14
  • 16
  • Ahh makes sense, while not completely new to kotlin I still don't know all of it of course. My thought process was that if the varargs will be treated as a array in the method, passing an already made array would be fine. Thanks for the ``*array`` tip. I'll add it when I get a chance, though I'll mark this as solved since I think this was my problem. Thanks :D – Zctrap Jun 13 '19 at 19:25