Skip to content

Repository files navigation

KopyBuilder

This is a compiler plugin that generates a builder class for Kotlin data classes. You can get and put properties in the builder, similar to a Map, and finally build a new instance.

Usage

Gradle Setup

Currently, it supports Kotlin versions 1.8, 1.9 and 2.x.

plugins {
id("io.github.windedge.kopybuilder") version "$version"
}

Version Compatibility

Below is a table showing the compatibility between KopyBuilder versions and Kotlin versions:

KopyBuilder VersionKotlin Version
0.1.61.8.x, 1.9.x
0.2.02.0.x - 2.1.10
0.2.32.1.20+
0.2.52.2.0 - 2.2.10
0.2.62.2.10
0.2.72.2.20+

Code Generation

For example, consider the following data class:

@KopyBuilder
data classUser(
valname:String,
valemail:String?
)

It will generate code like this:

publicclassUserBuilder: io.github.windedge.copybuilder.CopyBuilder<User> {
overridefun`get`(key:String): Any? {
//...
}
overridefunput(key:String, `value`: Any?) {
//...
}
overridefunbuild(): User=User(name =..., email =... )
}
fun User.toCopyBuilder(): CopyBuilder<User> =...
fun User.copyBuild(initialize:CopyBuilder<User>.() ->Unit): User { /*...*/ }

You can use it as follows:

val user =User(...)
val builder = user.toCopyBuilder()
builder.apply {
put("name", ...)
put("email", ...)
}
val newUser = builder.build()
// Or build with copyBuild directlyval newUser = user.copyBuild {
put("name", ...)
}

You can even use it in a reflection way, making it possible to cooperate with 3rd party libraries:

importio.github.windedge.copybuilder.CopyBuilderHostif (CopyBuilderHost::class.isInstance(user)) {
@Suppress("CAST_NEVER_SUCCEEDS")
val host = user asCopyBuilderHost<User>
val newUser = host.copyBuild {
put("name", "Max")
}
}

License

This project is licensed under the MIT License. Please refer to the LICENSE file for details.

About

Generate Map-like builders for Kotlin data classes with get/put/build capabilities.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages