How do I build a constructor where the field is `var` and can be `@annotated`?

283 Views Asked by At

How do I use Kotlinpoet to generate the following code?

data class Test (
  @Id
  var id: Long
) : Interface {
  override fun primaryKey() : Serializable = this
}
2

There are 2 best solutions below

0
On

with Yrii‘s answer, you also need call

addProperty(PropertySpec.builder("id",Long::class).initializer("id").build())
0
On

You can try

FileSpec
                .builder(packageName, actionName)
                .addType(TypeSpec.classBuilder(actionName)
                        .primaryConstructor(FunSpec.constructorBuilder()
                                .addParameter(ParameterSpec.builder("aName", String::class.java)
                                        .addAnnotation(Id::class.java)
                                        .build())
                                .build()).build())