Skip to content

Instantly share code, notes, and snippets.

@williamokano
Created May 1, 2020 08:52
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 williamokano/07d193896f368c460af11f703351e7f5 to your computer and use it in GitHub Desktop.
Save williamokano/07d193896f368c460af11f703351e7f5 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