Skip to content

Instantly share code, notes, and snippets.

@balsikandar-okcredit
Last active January 19, 2020 19:57
Show Gist options
  • Save balsikandar-okcredit/49acbbdc4a1dad9c85ebc09b65402d05 to your computer and use it in GitHub Desktop.
Save balsikandar-okcredit/49acbbdc4a1dad9c85ebc09b65402d05 to your computer and use it in GitHub Desktop.
Kotlin DSL an improvement over Builder pattern
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