Last active
January 23, 2019 07:44
-
-
Save halilozercan/53e2d297beb0a4e9aa0d4c5c72269bbd to your computer and use it in GitHub Desktop.
Builder pattern in Kotlin
This file contains 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
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.