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

- 1,777
- 1
- 21
- 27
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!

- 1,777
- 1
- 21
- 27
-
This is the correct answer. This drop in function is super helpful. – spierce7 Jan 26 '23 at 05:00
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.

- 39,695
- 10
- 113
- 130
-
3Curious why this decision was taken, since Kotlin coding convention recommends removing redundant public modifier. https://kotlinlang.org/docs/reference/coding-conventions.html#modifiers – Abhishek Dec 15 '20 at 19:30
-
2`Unless you're working on a library, omit redundant modifiers (e.g. public).` KotlinPoet is often used by higher-level libraries that generate code (such as SQLDelight, Wire). For this kind of libraries, the correctness of generated code is very important, and code style is not that important. Explicit API mode helps prevent subtle bugs that may stem from omitting modifiers and explicit types. – Egor Dec 15 '20 at 20:57
-
I understand your perspective, but I respectfully disagree. In my opinion, a library should aim to be versatile and useful in a wide range of situations. By providing flexible code utilities that can be adapted to different needs. – Ibrahim AlTamimi Mar 17 '23 at 12:51