I am stuck on this feature, below is the expected code to be generated, and the total number of parameters is not a fix number, there might be 2, or 3 or more.
val instance: InstanceType = Instance(parameter1, parameter2)
this is within one function, so I only know that I should use .addCode(CodeBlock.of("%L", PropertySpec))
But I don't find a way to define the code block with a dynamic parameters need to be passed in. Any suggestion?
There are two ways to solve this. First, CodeBlock has a Builder which allows you to construct it dynamically. Here's an example:
@Test fun manyParams() {
val instanceType = ClassName("", "InstanceType")
val instance = ClassName("", "Instance")
val params = listOf("param1", "param2")
val prop = PropertySpec.builder("instance", instanceType)
.initializer(CodeBlock.builder()
.add("%T(", instance)
.apply {
params.forEachIndexed { index, param ->
if (index > 0) add(",%W")
add(param)
}
}
.add(")")
.build())
.build()
assertThat(prop.toString()).isEqualTo("""
|val instance: InstanceType = Instance(param1, param2)
|""".trimMargin())
}
Second, you can create a separate CodeBlock for each parameter and join them:
@Test fun manyParams() {
val instanceType = ClassName("", "InstanceType")
val instance = ClassName("", "Instance")
val params = listOf("param1", "param2")
val paramCodeBlocks = params.map { CodeBlock.of(it) }
val prop = PropertySpec.builder("instance", instanceType)
.initializer("%T(%L)", instance, paramCodeBlocks.joinToCode(separator = ",%W"))
.build()
assertThat(prop.toString()).isEqualTo("""
|val instance: InstanceType = Instance(param1, param2)
|""".trimMargin())
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With