Kotlin Builder example refactor (#4895)

* encoding

* Refactor builder

* Usage

* Builder as data class
This commit is contained in:
Grzegorz Piwowarek 2018-08-18 14:01:01 +02:00 committed by GitHub
parent 8c4585bc46
commit cb86a05efd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 26 additions and 34 deletions

View File

@ -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)
}
}

View File

@ -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)

View File

@ -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) }
}