🏗 Automatically generating builders 👷 for Kotlin data classes
.
(incremental)
For a working usage of this library see the sample/
module.
-
(optional - for Android projects) add to your app's
build.gradle
:android { kotlinOptions.jvmTarget = '1.8' }
-
Add to
@DataClassBuilder
annotation yourdata class
@DataClassBuilder data class User( val name: String = "Anonymous", val age: Int, val photoUrl: String? = null ) { companion object //<-- OPTIONAL companion object }
-
Use the generated builder to create your
data class
://1. Java-style builder val jane = dataClassBuilder(User::class) .name("Jane") .age(30) .build()
or
//2. Kotlin DSL builder val jane = buildDataClass(User::class) { name = "Jane" age = 30 }
or
//3. Java-style builder through companion (generated if companion is present) val jane = User.dataClassBuilder() .name("Jane") .age(30) .build()
or
//4. Kotlin DSL builder through companion (generated if companion is present) val jane = User.buildDataClass { name = "Jane" age = 30 }
For easy interoperation with Java code add this companion object
to your data class
:
@DataClassBuilder
data class User(
val name: String = "Anonymous",
val age: Int,
val photoUrl: String? = null
) {
companion object {
@JvmStatic
fun builder() = dataClassBuilder(User::class) //NOT specifying return type explicitly on purpose
}
}
(something like this might be generated by the library in one of the future implementations)
Add in your build.gradle
:
repositories {
maven { url 'https://dl.bintray.com/blipinsk/maven/' }
}
dependencies {
kapt "com.bartoszlipinski:data-class-builder-compiler:0.1.0"
implementation "com.bartoszlipinski:data-class-builder:0.1.0"
}
The presence of data class
parameters is verified in runtime.
E.g.
-
For
data class
:@DataClassBuilder data class User( val name: String = "Anonymous", val age: Int // <-- no default value specified )
-
When creating:
buildDataClass(User::class) { name = "John" // not setting the necessary `age` }
-
☝️ this will crash 💥 in runtime ☝️
- Bartosz Lipiński
Copyright 2020 Bartosz Lipiński
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.