Kotlin Builder example refactor (#4895)
* encoding * Refactor builder * Usage * Builder as data class
This commit is contained in:
parent
8c4585bc46
commit
cb86a05efd
|
@ -1,39 +1,22 @@
|
|||
package com.baeldung.builder
|
||||
|
||||
class FoodOrder private constructor(builder: FoodOrder.Builder) {
|
||||
|
||||
val bread: String?
|
||||
val condiments: String?
|
||||
val meat: String?
|
||||
val fish: String?
|
||||
|
||||
init {
|
||||
this.bread = builder.bread
|
||||
this.condiments = builder.condiments
|
||||
this.meat = builder.meat
|
||||
this.fish = builder.fish
|
||||
}
|
||||
|
||||
class Builder {
|
||||
|
||||
var bread: String? = null
|
||||
private set
|
||||
var condiments: String? = null
|
||||
private set
|
||||
var meat: String? = null
|
||||
private set
|
||||
var fish: String? = null
|
||||
private set
|
||||
class FoodOrder(
|
||||
val bread: String?,
|
||||
val condiments: String?,
|
||||
val meat: String?,
|
||||
val fish: String?
|
||||
) {
|
||||
data class Builder(
|
||||
var bread: String? = null,
|
||||
var condiments: String? = null,
|
||||
var meat: String? = null,
|
||||
var fish: String? = null) {
|
||||
|
||||
fun bread(bread: String) = apply { this.bread = bread }
|
||||
|
||||
fun condiments(condiments: String) = apply { this.condiments = condiments }
|
||||
|
||||
fun meat(meat: String) = apply { this.meat = meat }
|
||||
|
||||
fun fish(fish: String) = apply { this.fish = fish }
|
||||
|
||||
fun build() = FoodOrder(this)
|
||||
|
||||
fun build() = FoodOrder(bread, condiments, meat, fish)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
package com.baeldung.builder
|
||||
|
||||
data class FoodOrderNamed(
|
||||
val bread: String? = null,
|
||||
val condiments: String? = null,
|
||||
val meat: String? = null,
|
||||
val fish: String? = null)
|
||||
val bread: String? = null,
|
||||
val condiments: String? = null,
|
||||
val meat: String? = null,
|
||||
val fish: String? = null)
|
||||
|
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.builder
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
FoodOrder.Builder()
|
||||
.bread("bread")
|
||||
.condiments("condiments")
|
||||
.meat("meat")
|
||||
.fish("bread").let { println(it) }
|
||||
}
|
Loading…
Reference in New Issue