Skip to content

Instantly share code, notes, and snippets.

@code-twister
Created February 21, 2019 23:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-twister/4449c550b13d4463409055d7bb7334ef to your computer and use it in GitHub Desktop.
Save code-twister/4449c550b13d4463409055d7bb7334ef to your computer and use it in GitHub Desktop.
Kotlin DSL Example
data class AddresBook(val contactGroups: List<ContactGroup>, val contacts: List<Contact>)
data class Contact(val name: String, val phones: List<String>)
data class ContactGroup(val name: String, val contacts: List<Contact>)
fun addressBook(lambda: AddressBookBuilder.()->Unit) = AddressBookBuilder().apply(lambda).build()
@DslMarker
annotation class AdressBookDslMarker
@AdressBookDslMarker
class AddressBookBuilder {
private val contacts: MutableList<Contact> = mutableListOf()
private val contactGroups: MutableList<ContactGroup> = mutableListOf()
fun contact(lambda: ContactBuilder.()->Unit) = contacts.add(ContactBuilder().apply(lambda).build())
fun contactGroup(lambda: ContactGroupBuilder.()->Unit) = contactGroups.add(ContactGroupBuilder().apply(lambda).build())
fun build() = AddresBook(contactGroups, contacts)
}
@AdressBookDslMarker
class ContactGroupBuilder {
var name: String = ""
private val contacts: MutableList<Contact> = mutableListOf()
fun contact(lambda: ContactBuilder.()->Unit) = contacts.add(ContactBuilder().apply(lambda).build())
fun build() = ContactGroup(name, contacts)
}
@AdressBookDslMarker
class ContactBuilder {
var name: String = ""
private val phones: MutableList<String> = mutableListOf()
fun phone(number: String) = phones.add(number)
fun build() = Contact(name, phones)
}
val myAddressBook = addressBook {
contact {
name = "John Doe"
phone("0712341234")
phone("4-93489")
}
contactGroup {
name = "friends"
contact {
name = "Jane"
phone("0712341234")
}
contact {
name = "Mr. T"
phone("0712341234")
}
}
}
val otherAdressBook = AddresBook(
listOf(
ContactGroup(
"friends",
listOf(
Contact(
"Jane",
listOf("0712341234")
),
Contact(
"Mr. T",
listOf("0712341234")
)
)
)
),
listOf(
Contact(
"John Doe",
listOf("4-93489", "0712341234")
)
)
)
fun main(args: Array<String>) {
println(myAddressBook)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment