基本语法
fun test(x : A.() -> Int){
val a = A()
a.x() // or x(a)
}
fun test(x : A.(c : Int) -> Int){
val a = A()
a.x(10) // or x(a,10)
}
举个例子
/**
* HTML
*/
class Html() {
private val header = Header()
private val body = Body()
fun header(h : Header.() -> Unit){
header.h() // or h(header)
}
fun body(b : Body.() -> Unit){
body.b() // or b(body)
}
override fun toString() : String = """
<html>
${header}
${body}
</html>
""".trimIndent()
}
/**
* Header
*/
class Header {
var title : String? = null
override fun toString() : String = """
<head><title>${title}</title></head>
""".trimIndent()
}
class Body {
val elems = mutableListOf<Element>()
fun p(text : String) = elems.add(P(text))
override fun toString() : String = """
<body>${ elems.joinToString("") }</body>
""".trimIndent()
}
interface Element {
}
class P(val content : String) : Element {
override fun toString(): String = """
<p>${content}</p>
""".trimIndent()
}
/**
* 测试
*/
class HtmlTest {
@Test
fun testA(){
val text = html{
header{
title = "hi"
}
body{
p("hhhh")
p("jhhhh")
}
}
println(text)
}
private fun html(h : Html.() -> Unit) : Html{
val html = Html()
html.h()
return html
}
}
网友评论