Skip to content

Instantly share code, notes, and snippets.

@halilozercan
Last active January 23, 2019 07:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save halilozercan/53e2d297beb0a4e9aa0d4c5c72269bbd to your computer and use it in GitHub Desktop.
Save halilozercan/53e2d297beb0a4e9aa0d4c5c72269bbd to your computer and use it in GitHub Desktop.
Builder pattern in Kotlin
abstract class BaseBuilder<T> {
abstract fun buildInternal(): T
}
fun <T, R: BaseBuilder<T>> R.build(block: R.() -> Unit): T {
block.invoke(this)
return this.buildInternal()
}
class Rectangle(
val x: Int,
val y: Int,
val width: Int,
val height: Int
) {
override fun toString(): String {
return "$x $y $width $height"
}
}
class RectangleBuilder : BaseBuilder<Rectangle>() {
private var x: Int = 0
private var y: Int = 0
private var width: Int = 0
private var height: Int = 0
fun setX(x: Int) {
this.x = x
}
fun setY(y: Int) {
this.y = y
}
fun setWidth(width: Int) {
this.width = width
}
fun setHeight(height: Int) {
this.height = height
}
override fun build(): Rectangle {
return Rectangle(x, y, width, height)
}
}
fun main() {
val rectangle = RectangleBuilder().build {
setX(12)
setY(24)
setWidth(3)
setHeight(4)
}
print(rectangle)
}
@halilozercan
Copy link
Author

This is an example of how to use Builder pattern in Kotlin.

Using BaseBuilder is optional and a bit discouraged tbh because there is a downside to that(buildInternal is public)

This is just a reference implementation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment