Skip to content

Instantly share code, notes, and snippets.

@hector6872
Last active December 10, 2019 20:49
Show Gist options
  • Save hector6872/698196535811bc8615c6059b927f19dc to your computer and use it in GitHub Desktop.
Save hector6872/698196535811bc8615c6059b927f19dc to your computer and use it in GitHub Desktop.
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