JJaviMS
JJaviMS

Reputation: 422

How to pass arguments to super using KotlinPoet

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?

Upvotes: 1

Views: 555

Answers (1)

JJaviMS
JJaviMS

Reputation: 422

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"))

Upvotes: 1

Related Questions