Skip to content

Instantly share code, notes, and snippets.

@moloccoGymondo
Created February 15, 2018 14:49
Show Gist options
  • Save moloccoGymondo/b2733bb9a96db5baab43b624bcfa44ec to your computer and use it in GitHub Desktop.
Save moloccoGymondo/b2733bb9a96db5baab43b624bcfa44ec to your computer and use it in GitHub Desktop.
Builders and data classes in kotlin
data class Car(
val model: String?,
val year: Int?,
val required: String?
) {
private constructor(builder: Builder) : this(builder.model, builder.year, builder.required)
companion object {
inline fun build(block: Builder.() -> Unit) = Builder().apply(block).build()
}
class Builder {
var required: String? = null
var model: String? = null
var year: Int? = null
fun build() = Car(this)
}
}
data class Car2(
val model: String,
val year: Int,
val required: String
)
data class Car3(
val model: String?,
val year: Int?,
val required: String
) {
private constructor(builder: Builder) : this(builder.model, builder.year, builder.required)
companion object {
inline fun build(required: String, block: Builder.() -> Unit) = Builder(required).apply(block).build()
}
class Builder(val required: String) {
var model: String? = null
var year: Int? = null
fun build() = Car3(this)
}
}
fun blah() {
val car = Car.build {
required = "Hi"
model = "Kryspin"
year = 2018
}
val car2 = Car2(
required = "Hi",
model = "Kryspin",
year = 2018
)
val car3 = Car3.build("Hi") {
model = "Kryspin"
year = 2018
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment