Created
October 21, 2016 13:35
-
-
Save sliskiCode/de8af1d769d5b81278d56ca83950890e to your computer and use it in GitHub Desktop.
Builders in Kotlin. Gist 3
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
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