Skip to content

Instantly share code, notes, and snippets.

@balsikandar
Created January 19, 2020 19:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save balsikandar/9ee6e96244ac7b5096a942b6953da9fd to your computer and use it in GitHub Desktop.
Save balsikandar/9ee6e96244ac7b5096a942b6953da9fd 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