Using Poet I'm trying to figure out how to get the...
# squarelibraries
i
Using Poet I'm trying to figure out how to get the type for a generated class. For example if you created a type and want to create an instance of it in the companion the desired code might look like this:
Copy code
data class Test(val input:String) {
    companion object {
        val example = Test("Hello")
    }
}
I can get as far as creating the data class and companion object but I'm not sure how to get the type
Test
, I'm using
Any
to get the code to generate but Any is the wrong type. It would be fine to just not have a type and maybe that is the solution but I'm not seeing a way to create a property without a type.
Copy code
FileSpec.builder("", "Test")
    .addType(
        TypeSpec.classBuilder("Test")
            .addModifiers(KModifier.DATA)
            .primaryConstructor(
                FunSpec.constructorBuilder()
                    .addParameter("input", String::class)
                    .build(),
            )
            .addProperty(
                PropertySpec.builder("input", String::class)
                    .initializer("input")
                    .build(),
            )
            .addType(
                TypeSpec.companionObjectBuilder()
                    .addProperty(
                        PropertySpec.builder("example", Any::class)
                            .initializer(CodeBlock.of("Test(\"Hello\")"))
                            .build(),
                    )
                    .build(),
            )
            .build(),
    )
    .build()
    .writeTo(generatedOutputDir)
output:
Copy code
public data class Test(
  public val input: String,
) {
  public companion object {
    public val example: Any = Test("Hello")
  }
}
j
There is no "self" type, so you have to create a
ClassName
using the target package and type name.
Generally I find it useful to create the
ClassName
first, and then use that to create the
FileSpec
and
TypeSpec
which both will accept `ClassName`s
i
Ah, ok that is what I was missing. I figured there has to be some way to create types that don't exist "yet". Thank you
i
And thanks for the tip, it is much nicer having the classname over repeating the strings in multiple places 👍