Skip to content

Instantly share code, notes, and snippets.

@blogscot
Created November 26, 2018 23:08
Show Gist options
  • Save blogscot/6b9197ddc8173a5d27c10c657574617d to your computer and use it in GitHub Desktop.
Save blogscot/6b9197ddc8173a5d27c10c657574617d to your computer and use it in GitHub Desktop.
Example of the Builder pattern using Kotlin
class Ship {
var name: String = ""
var crewSize: Int = 0
var numMasts: Int = 0
override fun toString(): String {
return "Ship { Name: $name, Num masts: $numMasts Crew Size: $crewSize}"
}
}
class Builder {
constructor(init: Builder.() -> Unit) {
init()
}
private var shipInfo: ShipInfo? = null
private var title: String = ""
fun setTitle(newTitle: String) {
title = newTitle
}
fun configure(init: ShipInfo.() -> Unit) {
shipInfo = ShipInfo().apply { init() }
}
fun build(): Ship {
val ship = Ship()
ship.name = title
shipInfo?.apply {
ship.crewSize = crewSize
ship.numMasts = numMasts
}
return ship
}
class ShipInfo {
var crewSize: Int = 0
var numMasts: Int = 0
}
}
fun main() {
val builder = Builder {
setTitle("Bonnie Lassie")
configure {
crewSize = 10
numMasts = 2
}
}
println(builder.build())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment