Replace KotlinPoet builders with Kotlin DSL
Lightweight Kotlin extension of KotlinPoet, providing Kotlin DSL functionality and other convenient solutions.
method("main") { ... }
is as good
as methods { "main" { ... } }
. Scroll down for more information.
buildFileSpec("com.example.helloworld", "HelloWorld") {
classType("HelloWorld") {
modifiers(PUBLIC, FINAL)
methods {
"main" {
modifiers(PUBLIC, STATIC)
returns = UNIT
parameter("args", STRING.array)
appendLine("%T.out.println(%S)", System::class, "Hello, KotlinPoet!")
}
}
}
}.writeTo(System.out)
repositories {
mavenCentral()
}
dependencies {
implementation "com.hendraanggrian:kotlinpoet-dsl:$version"
}
T::class
as parameters
KClass<*>
can now be used as format arguments. There is also inline reified
type function whenever possible.
buildMethodSpec("sortList") {
returns = int
parameters.add(classNamed("java.util", "List").parameterizedBy(hoverboard), "list")
appendLine("%T.sort(list)", Collections::class)
appendLine("return list")
}
buildFieldSpec("count", INT) {
initializer("%L", 0)
}
Some elements (field, method, parameter, etc.) are wrapped in container class. These containers have ability to add components with/without invoking DSL.
For example, 2 examples below will produce the same result.
types.addClass("Car") {
methods {
"getWheels" {
returns = INT
appendLine("return wheels")
}
"setWheels" {
parameter("wheels", INT)
appendLine("this.wheels = wheels")
}
}
}
types.addClass("Car") {
method("getWheels") {
returns = INT
appendLine("return wheels")
}
method("setWheels") {
paraneter("wheels", INT)
appendLine("this.wheels = wheels")
}
}
In spirit of Gradle Kotlin DSL, creating a spec can be done by delegating to a property.
val title by parametering(String::class) {
annotation<NotNull>
}
val message by parametering(String::class) {
annotation<Nullable>
}
Write TypeName
and all its subtypes fluently.
val myClass: ClassName =
classNamed("com.example", "MyClass")
val listener: LambdaTypeName =
STRING.lambdaBy(returns = UNIT)
val memberOfString: MemberTypeName =
myClass.memberOf("myField")
val pairOfInteger: ParameterizedTypeName =
Pair::class.name.parameterizedBy(Int::class, Int::class)
val tVariable: TypeVariableName =
"T".generics
val producerOfCharSequence: WildcardTypeName =
CharSequence::class.name.producerOf()