DSL(Domain Specific Language)은 복잡한 객체, 계층 구조를 갖고 있는 객체들을 정의할 때 굉장히 유용
// 코틀린 DSL을 통해 표현한 HTML
body {
div {
a("<https://kotlinlang.org>") {
target = ATarget.blank
+"Main site"
}
}
+"Some content"
}
// Main site
// Some content
// Android View DSL
verticalLayout {
val name = editText()
button("Say Hello") {
onClick { toast("Hello, ${name.text}!") }
}
}
// Ktor API
fun Routing.api() {
route("news") {
get {
val newsData = NewsUseCase.getAcceptedNews()
call.respond(newsData)
}
get("propositions") {
requireSecret()
...
}
}
}
// kotest
class LawyerSearchTest : BehaviorSpec(
{
given("LawyerSearchTest") {
`when`("랜덤으로 셔플할 변호사가 8명보다 적은 경우,") {
then("셔플링 없이 모든 변호사를 그대로 반환한다.") {
val sut = List(5) { LawyerSearchFixture.create(lawyerId = it.toLong()) }
val actual = LawyerSearch.getShuffledLawyerSearches(sut)
assertSoftly {
actual.size shouldBe sut.size
actual shouldBe sut
}
}
}
}
},
)
// gradle.kts
plugins {
'java-library'
}
dependencies {
api("junit...")
implementation(...)
testImplementation(...)
}
...
// predicate에 함수 타입이 활용
public inline fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T> {
return filterTo(ArrayList<T>(), predicate)
}
함수 타입의 몇 가지 예
() → Unit
: 아규먼트를 갖지 않고, Unit 반환