Search code examples
kotlinpoet

How to make method return type of generated class in KotlinPoet?


I need to generate a Builder class with the help of KotlinPoet. For this purpose, I need to make the method return the Builder type. I do it in the following way:

    private fun generateInitUserBehaviorClass() = TypeSpec.classBuilder("Init")
    .addType(generateInitBuilderClass())
    .build()

private fun generateInitBuilderClass() = TypeSpec.classBuilder("Builder")
    .addProperty(generateInitBuilderEndpointProperty())
    .addFunction(generateInitBuilderEndpointSetter())
    .build()

private fun generateInitBuilderEndpointProperty() = PropertySpec.builder(
    "endpoint",
    Class.forName("android.net.Uri").asTypeName().copy(nullable = true),
    KModifier.PRIVATE
).mutable(true)
    .initializer("null")
    .build()

private fun generateInitBuilderEndpointSetter() = FunSpec.builder("setEndpoint")
    .addParameter("endpoint", Class.forName("android.net.Uri"))
    .returns(Class.forName("com.idfinance.userbehavior.utils.Init.Builder"))
    .build()

But when I build the module I catch the error that Class.forName("com.idfinance.userbehavior.utils.Init.Builder") cannot find class Builder. The package is correct and as I understand the problem is that I try to use class as return type when it is not generated yet. But how can I solve this problem?


Solution

  • You can just instantiate a ClassName using its constructor, it does not have to be a declared class:

    private fun generateInitBuilderEndpointSetter() = FunSpec.builder("setEndpoint")
        .addParameter("endpoint", ClassName("android.net", "Uri"))
        .returns(ClassName("com.idfinance.userbehavior.utils", "Init", "Builder"))
        .build()