fun main(args:Array):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 () fun aa(p:AA.()->Unit){ val aa = AA(); aa.p(); children.add(aa); } override fun toString(): String { val builder = StringBuilder(" ") children.forEach { builder.append(it.toString()) } builder.append("\r\n") return builder.toString(); }}class AA { val children=arrayListOf () operator fun String.unaryPlus() { children.add("\r\n\t\t ${this} ") } override fun toString(): String { val builder = StringBuilder("\r\n\t") children.forEach { builder.append(it.toString()) } builder.append("\r\n\t ") return builder.toString(); }}
执行结果
import java.util.*import List.Companion.listimport Map.Companion.mapfun main(args: Array): 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 () { 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 () { companion object { fun map(p: Map.() -> Unit): Map { val m = Map() m.p() return m } } fun values(vararg x: Pair ) { 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]}