Created
January 12, 2017 18:58
-
-
Save markus2610/1bf21e40839e409016f6d02652de94f0 to your computer and use it in GitHub Desktop.
Builder Pattern Kotlin
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
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