Kotlinpoet: Ommitting redundant `public` modifier from generated types and properties

Viewed 817

Is there any way to omit the redundant public modifier from types and properties generated via KotlinPoet's TypeSpec.Builder and PropertySpec.Builder respectively?

2 Answers

Egor's answer above is the correct one. There is no way to omit redundant public modifiers in KotlinPoet, and there is good reason for that.

However, all those (unnecessary in my case) warnings were getting to my nerves and I had to find some way to get rid of them. What I finally came up with, is to suppress them in KotlinPoet-generated files.

Here's an extension for FileSpec.Builder that enables you to suppress warnings for a particular generated file.

internal fun FileSpec.Builder.suppressWarningTypes(vararg types: String) {
    if (types.isEmpty()) {
        return
    }

    val format = "%S,".repeat(types.count()).trimEnd(',')
    addAnnotation(
        AnnotationSpec.builder(ClassName("", "Suppress"))
            .addMember(format, *types)
            .build()
    )
}

And here's an example of how to use it to get rid of the redundant visibility modifiers warning in generated files:

val fileBuilder = FileSpec.builder(myPackageName, myClassName)
fileBuilder.suppressWarningTypes("RedundantVisibilityModifier")

The extension also supports suppressing more than one warning types:

fileBuilder.suppressWarningTypes("RedundantVisibilityModifier", "USELESS_CAST")

Please note that I'm in no way suggesting that you should get rid of ALL the warnings that bother you in your generated code! Use this code carefully!

No, and no plans to support such functionality. If it's important for your use case to not have explicit public modifiers, a good solution would be to post-process the output with a script that removes them.

Related