Skip to content

Instantly share code, notes, and snippets.

@kathisai
Created August 27, 2021 18:36
Show Gist options
  • Select an option

  • Save kathisai/c3d0dca4a362d5c95001dbd44ef761e0 to your computer and use it in GitHub Desktop.

Select an option

Save kathisai/c3d0dca4a362d5c95001dbd44ef761e0 to your computer and use it in GitHub Desktop.
simplified Kotlin type safe builder example
// 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