Building DSL-like APIs
Use infix for clarity.
Infix for Clarity
Infix functions are a building block of Kotlin DSLs (domain-specific languages). They make API calls read like natural phrases.
infix fun String.eq(value: String) = this == value
fun main() {
println("on" eq "on")
}A Fluent Builder Idea
Combining infix with small types lets you express intent declaratively.
class Query(val field: String) {
infix fun equals(value: String) = "$field = '$value'"
}
fun main() {
val q = Query("name") equals "Sam"
println(q)
}All lessons in this course
- Infix Functions
- Building DSL-like APIs
- tailrec Functions
- When to Use Each