Skip to content

Instantly share code, notes, and snippets.

@sliskiCode
Created October 21, 2016 13:35
Show Gist options
  • Save sliskiCode/de8af1d769d5b81278d56ca83950890e to your computer and use it in GitHub Desktop.
Save sliskiCode/de8af1d769d5b81278d56ca83950890e to your computer and use it in GitHub Desktop.
Builders in Kotlin. Gist 3
class Person private constructor(val name: String, val surname: String, val age: Int) {
private constructor(builder: Builder) : this(builder.name, builder.surname, builder.age)
companion object {
fun create(init: Builder.() -> Unit) = Builder(init).build()
}
class Builder private constructor() {
constructor(init: Builder.() -> Unit) : this() {
init()
}
lateinit var name: String
lateinit var surname: String
var age: Int = 0
fun name(init: Builder.() -> String) = apply { name = init() }
fun surname(init: Builder.() -> String) = apply { surname = init() }
fun age(init: Builder.() -> Int) = apply { age = init() }
fun build() = Person(this)
}
}
fun main(args: Array<String>) {
Person.create {
name { "Peter" }
surname { "Slesarew" }
age { 28 }
}
// OR
Person.create {
name = "Peter"
surname = "Slesarew"
age = 28
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment