Skip to content

Instantly share code, notes, and snippets.

@hrules6872
Last active Dec 10, 2019
Embed
What would you like to do?
Kotlin DSL example
@DslMarker
annotation class HorizontalSelectorGroups
interface HorizontalSelectorHelper {
fun groups(block: GroupsBuilder.() -> Unit): List<Pair<Header, List<Item>>> = GroupsBuilder().apply(block).build()
@HorizontalSelectorGroups
class GroupsBuilder {
private val groups = mutableListOf<Group>()
fun group(block: GroupBuilder.() -> Unit) {
groups.add(GroupBuilder().apply(block).build())
}
fun build(): List<Pair<Header, List<Item>>> = groups.map { group -> Pair(group.header, group.items) }
}
class Group(
val header: Header,
val items: List<Item>
)
@HorizontalSelectorGroups
class GroupBuilder {
var header = Header()
private val items = mutableListOf<Item>()
fun items(block: ItemsBuilder.() -> Unit) {
items.addAll(ItemsBuilder().apply(block).build())
}
fun build(): Group =
Group(header = header, items = items)
}
@HorizontalSelectorGroups
class ItemsBuilder {
private val items = mutableListOf<Item>()
operator fun Item.unaryPlus() {
items += this
}
operator fun Item.unaryMinus() {
items += this
}
fun item(block: ItemBuilder.() -> Unit) {
items.add(ItemBuilder().apply(block).build())
}
fun build() = items
}
@HorizontalSelectorGroups
class ItemBuilder {
var uuid: String = String.EMPTY
var title: String = String.EMPTY
fun build() = Item(uuid = uuid, title = title)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment