Three builder pattern ways in Kotlin.
Last active
October 20, 2016 01:20
-
-
Save pokk/e8027f23c6b3dcdb605ccdfd8f0703f4 to your computer and use it in GitHub Desktop.
Three builder method in Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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