Created
August 27, 2021 18:36
-
-
Save kathisai/c3d0dca4a362d5c95001dbd44ef761e0 to your computer and use it in GitHub Desktop.
simplified Kotlin type safe builder example
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
| // Lets say I wanted to build a Car | |
| // -> wheel | |
| // -> engine | |
| // -> body | |
| fun main() { | |
| //This is possible with type Safe builders and DSL | |
| car { | |
| // this: Car | |
| wheel { | |
| // thisL Wheel | |
| createWheel() | |
| } | |
| engine { | |
| //thisL Engine | |
| createEngine() | |
| } | |
| body { | |
| //this: Body | |
| createBody() | |
| } | |
| } | |
| } | |
| fun car(carBuilder: Car.() -> Unit): Car { | |
| val car = Car() | |
| car.carBuilder() | |
| return car | |
| } | |
| class Car() { | |
| fun wheel(wheelBuilder: Wheel.() -> Unit) { | |
| val wheel = Wheel() | |
| wheel.wheelBuilder() | |
| } | |
| fun engine(engineBuilder: Engine.() -> Unit) { | |
| val engine = Engine() | |
| engine.engineBuilder() | |
| } | |
| fun body(bodyBuilder: Body.() -> Unit) { | |
| val body = Body() | |
| body.bodyBuilder() | |
| } | |
| } | |
| class Wheel { | |
| fun createWheel() { | |
| TODO("Not yet implemented") | |
| } | |
| } | |
| class Engine { | |
| fun createEngine() { | |
| TODO("Not yet implemented") | |
| } | |
| } | |
| class Body { | |
| fun createBody() { | |
| TODO("Not yet implemented") | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment