1

I am using KotlinPoet to generate some code. I have an abstract class with some parameters. Let´s say:

abstract class Foo (val foo: String)

And I want to use Kotlin Poet so I can create an implementation of this class in the following way:

class Bar (val bar: String) : Foo ("I am bar")

My code generation looks this way:

// Create the constructor function
val constructorSpec = FunSpec.constructorBuilder().addParameter("bar", String::class)

// Create the property definition
val propertySpec = PropertySpec.builder("bar",String::class).initializer("bar").build()

// Create the class definition
val classSpec = TypeSpec.classBuilder("Bar").superclass(Foo::class).primaryConstructor(constructorSpec).
    .addProperty(propertySpec)

I have try this two ways to get the results, but none of them worked:

// First method using the TypeSpec
classSpec.addSuperclassConstructorParameter(CodeBlock.of("%S","I am bar"))

// Second method using the FunSpec
constructorSpec.callSuperConstructor(CodeBlock.of("%S","I am bar"))

Is there any way I can achieve passing parameters to the super class?

JJaviMS
  • 392
  • 6
  • 18
  • Can you please clarify what you mean by "none of them worked"? What exactly are you seeing when trying both of the options? Here's an example unit test that uses `addSuperclassConstructorParameter()` and produces the output similar to what you're looking for: https://github.com/square/kotlinpoet/blob/master/kotlinpoet/src/test/java/com/squareup/kotlinpoet/TypeSpecTest.kt#L3856-L3871 – Egor Feb 08 '23 at 22:08

1 Answers1

0

After a lot of issues I finally found the problem, gradle was not executing the ksp task due the cache, so I could only see the old version of the processor.

The one that had work for me was:

classSpec.addSuperclassConstructorParameter(CodeBlock.of("%S","I am bar"))
JJaviMS
  • 392
  • 6
  • 18