Skip to content

Instantly share code, notes, and snippets.

@pokk
Last active October 20, 2016 01:20
Show Gist options
  • Save pokk/e8027f23c6b3dcdb605ccdfd8f0703f4 to your computer and use it in GitHub Desktop.
Save pokk/e8027f23c6b3dcdb605ccdfd8f0703f4 to your computer and use it in GitHub Desktop.
Three builder method in Kotlin
class Car( //add private constructor if necessary
val model: String?,
val year: Int
) {
private constructor(builder: Builder) : this(builder.model, builder.year)
class Builder {
var model: String? = null
private set
var year: Int = 0
private set
fun model(model: String): Builder {
this.model = model
return this
}
fun year(year: Int): Builder {
this.year = year
return this
}
fun build() = Car(this)
}
}
// Usage
val car = Car.Builder().model("BMW").build()
class Car ( //add private constructor if necessary
val model: String?,
val year: Int
) {
private constructor(builder: Builder) : this(builder.model, builder.year)
companion object {
inline fun build(block: Builder.() -> Unit) = Builder().apply(block).build()
}
class Builder {
var model: String? = null
var year: Int = 0
fun build() = Car(this)
}
}
// Usage
val car = Car.build { model = "BMW" }
class Car ( //add private constructor if necessary
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 = 0
fun build() = Car(this)
}
}
// Usage
val car = Car.build(required = "value") { model = "BMW" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment