Created
February 21, 2019 23:10
-
-
Save code-twister/4449c550b13d4463409055d7bb7334ef to your computer and use it in GitHub Desktop.
Kotlin DSL Example
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
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