Skip to content

Instantly share code, notes, and snippets.

@philipphofmann
Last active October 26, 2018 13:42
Show Gist options
  • Save philipphofmann/e4be03013504214611e0ad0ac1416294 to your computer and use it in GitHub Desktop.
Save philipphofmann/e4be03013504214611e0ad0ac1416294 to your computer and use it in GitHub Desktop.
Workshop: Creating DSLs in Kotlin by Hadi Hariri
@DslMarker
annotation class CloudProviderDSL
data class Configuration(
val provider: String,
val region: String,
val isActive: Boolean,
val fallback: Int,
val servers: List<Server>
)
data class Server(
val hostname: String,
val name: String,
val description: String
)
@CloudProviderDSL
class ConfigurationBuilder {
var provider: String = ""
var region: String = ""
var isActive: Boolean = false
var fallback: Int = 0
private var servers = mutableListOf<Server>()
fun servers(block: SERVERS.() -> Unit) {
servers.addAll(SERVERS().apply(block))
}
fun build(): Configuration =
Configuration(provider, region, isActive, fallback, servers)
}
@CloudProviderDSL
class SERVERS : ArrayList<Server>() {
fun server(block: ServerBuilder.() -> Unit) {
add(ServerBuilder().apply(block).build())
}
}
@CloudProviderDSL
class ServerBuilder {
fun build(): Server = Server(hostname, name, description)
var hostname: String = ""
var name: String = ""
var description: String = ""
}
fun configuration(block: ConfigurationBuilder.() -> Unit) = ConfigurationBuilder().apply(block).build()
fun main() {
val config = configuration {
provider = "Google"
region = "eu-west-1"
isActive = true
fallback = 10
servers {
server {
hostname = ""
name = "persistence 1"
description = "Provides persistence mechanism"
}
server {
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment