Created
January 19, 2020 19:59
-
-
Save balsikandar/9ee6e96244ac7b5096a942b6953da9fd to your computer and use it in GitHub Desktop.
Kotlin DSL an improvement over Builder pattern
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 Student( | |
val name: String?, | |
val standard: Int, | |
val rollNumber: Int | |
) { | |
private constructor(builder: Builder) : this(builder.name, builder.standard, builder.rollNumber) | |
companion object { | |
inline fun student(block: Student.Builder.() -> Unit) = Student.Builder().apply(block).build() | |
} | |
class Builder { | |
var name: String? = null | |
var standard: Int = 0 | |
var rollNumber: Int = 0 | |
fun build() = Student(this) | |
} | |
} | |
//To create Student object now we can use | |
student { | |
name = "Alex" | |
standard = 10 | |
rollNumber = 720 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment