Skip to content

Instantly share code, notes, and snippets.

@Brunomachadob
Created May 1, 2020 12:45
Show Gist options
  • Save Brunomachadob/de3239a29542c85831fa9aa8500b77fd to your computer and use it in GitHub Desktop.
Save Brunomachadob/de3239a29542c85831fa9aa8500b77fd to your computer and use it in GitHub Desktop.
Kotlin DSL
data class Request(
val method: String,
val path: String,
val headers: Map<String, String>
)
class RequestBuilder {
private lateinit var method: String
private lateinit var path: String
private var headers = mutableMapOf<String, String>()
fun method(get: () -> String) = apply {
method = get()
}
fun path(get: () -> String) = apply {
path = get()
}
fun header(get: () -> Pair<String, String>) = get()
.also { (key, value) ->
headers[key] = value
}
fun build(): Request = Request(method, path, headers)
}
fun request(builder: RequestBuilder.() -> Unit) = RequestBuilder().apply(builder).build()
val request = request {
method { "GET" }
path { "/path" }
header { "name" to "value" }
}
println(request) // Request(method=GET, path=/path, headers={name=value})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment