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.
Currently, it supports Kotlin versions 1.8, 1.9 and 2.x.
plugins {
id("io.github.windedge.kopybuilder") version "$version"
}
Below is a table showing the compatibility between KopyBuilder versions and Kotlin versions:
| KopyBuilder Version | Kotlin Version |
|---|---|
| 0.1.6 | 1.8.x, 1.9.x |
| 0.2.0 | 2.0.x - 2.1.10 |
| 0.2.3 | 2.1.20+ |
| 0.2.5 | 2.2.0 - 2.2.10 |
| 0.2.6 | 2.2.10 |
| 0.2.7 | 2.2.20+ |
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")
}
}
This project is licensed under the MIT License. Please refer to the LICENSE file for details.