An example of a builder pattern in Kotlin.
Table of contents for design patterns in Kotlin
The builder pattern is a design pattern designed to provide a flexible solution to various object creation problems in object-oriented programming. The intent of the Builder design pattern is to separate the construction of a complex object from its representation. It is one of the Gang of Four design patterns. Wikipedia
Example:
data class Order private constructor(
val uid: String,
val date: LocalDateTime,
val total: BigDecimal
) {
class Builder() {
private var uid: String = ""
private var date: LocalDateTime = LocalDateTime.now()
private var total: BigDecimal = BigDecimal.ZERO
constructor(initBuilder: Builder.() -> Unit) : this() {
initBuilder()
}
fun uid(uid: String): Builder = apply { this.uid = uid }
fun date(date: String): Builder = date(LocalDateTime.parse(date))
fun date(date: LocalDateTime): Builder = apply { this.date = date }
fun total(total: Double): Builder = total(BigDecimal.valueOf(total))
fun total(total: BigDecimal): Builder = apply { this.total = total }
fun build() = Order(
uid = this.uid,
date = this.date,
total = this.total
)
}
companion object {
fun order(init: Builder.() -> Unit): Order = Builder(init).build()
}
}
Usage:
fun main() {
val order = order {
uid("ed37eae6-c32e-49ee-887b-52d829455c70")
date("2018-10-23T17:19:33")
total(1024.00)
}
print(order)
}
Result
Order(uid=ed37eae6-c32e-49ee-887b-52d829455c70, date=2018-10-23T17:19:33, total=1024.0)