TIL

아이템 35 복잡한 객체를 생성하기 위한 DSL을 정의하라

// HTML을 표현하는 DSL
body {
	div {
		a("https:/kotlinlang.org") {
			target = ATarget.blank
			+"Main Site"
		}
	}
}
fun Routing.api() {
	route("news") {
		get {
			val newsData = NewsUseCase.getAcceptedNews()
			call.responsd(newsData)
		}
		get("propositions") {
			requireSecret()
			val newsData = NewsUseCase.getPropositions()
			call.respond(newsData)
		}
	}
}

사용자 정의 DSL 만들기

fun plus(a: Int, b: Int) = a + b // 일반 함수

val plus1: (Int, Int) -> Int = { a, b -> a + b } // 람다 표현식
val plus2: (Int, Int) -> Int = fun(a, b) = a + b // 익명 함수
val plus3: (Int, Int) -> Int = ::plus // 함수 레퍼런스
val myPlus = fun Int.(other: Int) = this + other
myPlus.invoke(1, 2) // invoke 사용
myPlus(1, 2) // 확장 함수가 아닌 함수처럼 사용
1.myPlus(2) // 확장 함수로 사용
fun createTable(): TableDSL = table {
	tr {
		for (i in 1..2) {
			td { +"this is column &i" }
		}
	}
}
fun table(init: TableBuilder.() -> Unit): TableBuilder { /*...*/ }

class TableBuilder {
	fun tr(init: TrBuilder.() -> Unit) { /*...*/ }
}

class TrBuilder {
	fun td(init: TdBuilder.() -> Unit) { /*...*/ }
}

언제 사용해야 할까?