Create DSL
FILE : BuildingDslDemo1.kt
In this short example we will see in depth how to build following syntax
dependencies {
compile("org.apache","commons","5.0")
compile("com.package","utils","2.1")
test("org.mockito","core","3.0")
}
This is just standard Kotlin code - no magic here. It can be also written in more explicit way :
DependenciesDsl.dependencies(fun DependenciesDsl.() {
this.compile("org.apache", "commons", "5.0")
this.compile("com.package", "utils", "2.1")
this.test("org.mockito", "core", "3.0")
})
External Function
companion object {
fun dependencies(buildDeps: DependenciesDsl.() -> Unit) { //1
val dsl = DependenciesDsl()
dsl.buildDeps() //2
// buildDeps(dsl) //2b
dsl.download() //3
}
// fun dependencies(buildDeps: DependenciesDsl.() -> Unit) = //4
// DependenciesDsl().apply(buildDeps).download()
}
- The type in a signature DependenciesDsl.() -> Unit is called "lambda with receiver" and can be understand as definition of extended function on DependenciesDsl in local context. This function is parameterless and returns unit so it can easilly be represented as simple {...} block
- Because of lambda with receiver definition from point 1 we have two choices of applying buildDeps lambda on locally created instance : with explicit and implicit receiver. Also remember that this the place where actual instance of dsl is created