3

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?

Jiachuan Li
  • 195
  • 9

1 Answers1

2

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())
}
Egor
  • 39,695
  • 10
  • 113
  • 130
  • Hi @Egor, thanks for your reply, but both two approaches need to define a params variable which is based on "listOf", but my scenario is I am not sure how many "param"s will be, there might be 2 or 3 or 4, so I don't know how to use a listOf for dynamical items. Any suggestion? – Jiachuan Li Jun 03 '18 at 13:56
  • Where are the params coming from? Can you post code that showcases the issue? – Egor Jun 06 '18 at 19:46