Skip to content

Instantly share code, notes, and snippets.

@williamokano
Created May 1, 2020 08:52
Show Gist options
  • Save williamokano/58234d7c67c5fead34a7bbd35b7f40e0 to your computer and use it in GitHub Desktop.
Save williamokano/58234d7c67c5fead34a7bbd35b7f40e0 to your computer and use it in GitHub Desktop.
Sample DSL example - Just playing around
package dev.okano.kotlin.coroutines.mains
data class Header(val name: String, val value: String)
data class HeaderBuilderDsl(val context: Request) {
companion object {
fun withContext(context: Request): HeaderBuilderDsl {
return HeaderBuilderDsl(context)
}
}
infix fun withName(name: String): PartialHeaderWithoutValue {
return PartialHeaderWithoutValue(context, name)
}
data class PartialHeaderWithoutValue(val context: Request, val name: String) {
infix fun andValue(value: String) {
context._headers.add(Header(name, value))
}
}
}
class Request {
val header = HeaderBuilderDsl.Companion
val context = this
val _headers = mutableListOf<Header>()
companion object {
operator fun invoke(init: Request.() -> Unit): Request =
Request().apply(init)
}
operator fun HeaderBuilderDsl.Companion.unaryPlus(): HeaderBuilderDsl {
return this.withContext(context)
}
fun getHeaders() = _headers.toList()
}
fun main(args: Array<String>) {
val request = Request {
+header withName "content-type" andValue "application/json"
+header withName "accept-language" andValue "en_US"
}
println(request.getHeaders())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment