fun main(args:Array<String>):Unit{
val x = a{
aa{
+"01.01"
+"01.02"
}
aa{
+"02.01"
+"02.02"
}
}
print(x)
}
fun a(p:A.()->Unit):A {
val a = A()
a.p()
return a;
}
class A {
val children=arrayListOf<AA>()
fun aa(p:AA.()->Unit){
val aa = AA();
aa.p();
children.add(aa);
}
override fun toString(): String {
val builder = StringBuilder("<a>")
children.forEach { builder.append(it.toString()) }
builder.append("
</a>")
return builder.toString();
}
}
class AA {
val children=arrayListOf<String>()
operator fun String.unaryPlus() {
children.add("
<text>${this}</text>")
}
override fun toString(): String {
val builder = StringBuilder("
<aa>")
children.forEach { builder.append(it.toString()) }
builder.append("
</aa>")
return builder.toString();
}
}
执行结果
<a> <aa> <text>01.01</text> <text>01.02</text> </aa> <aa> <text>02.01</text> <text>02.02</text> </aa> </a>
import java.util.*
import List.Companion.list
import Map.Companion.map
fun main(args: Array<String>): Unit {
val x = list {
values("a", "b", "c")
list {
values("a", "b", "c")
map {
values("name" to "Fred")
}
}
map {
values(
"name" to "Fred",
"age" to "28",
"fav" to list {
values("java", "c++", "kotlin")
}
)
}
}
val y = map {
values("languages" to list {
values("java", "c++", "perl")
values("scala","kotlin","ruby")
})
}
println(x)
println(y)
}
class List : ArrayList<Any>() {
companion object {
fun list(p: List.() -> Unit): List {
val l = List()
l.p()
return l
}
}
fun values(vararg x: Any) {
this.addAll(x)
}
fun list(p: List.() -> Unit) {
val l = List()
l.p()
this.add(l as Any)
}
fun map(p: Map.() -> Unit) {
val m = Map()
m.p()
this.add(m as Any)
}
}
class Map : HashMap<String, Any>() {
companion object {
fun map(p: Map.() -> Unit): Map {
val m = Map()
m.p()
return m
}
}
fun values(vararg x: Pair<String, Any>) {
this.putAll(x)
}
fun list(p: List.() -> Unit): List {
val l = List()
l.p()
return l;
}
fun map(p: Map.() -> Unit): Map {
val m = Map()
m.p()
return m
}
}
执行结果
[a, b, c, [a, b, c, {name=Fred}], {name=Fred, fav=[java, c++, kotlin], age=28}]
{languages=[java, c++, perl, scala, kotlin, ruby]}