CodeToLive

Kotlin Extensions & DSLs

Learn about extension functions and domain-specific languages in Kotlin.

Extension Functions

// Add function to String class
fun String.addExclamation(): String {
    return "$this!"
}

println("Hello".addExclamation())  // Hello!

// Extension property
val String.lastChar: Char
    get() = this[length - 1]

println("Kotlin".lastChar)  // n

Extension Functions with Nullable Receiver

fun String?.orEmpty(): String {
    return this ?: ""
}

val s: String? = null
println(s.orEmpty())  // ""

Scope Functions

// let - execute block with non-null object
nullableString?.let { 
    println(it.length) 
}

// apply - configure object
val person = Person().apply {
    name = "Alice"
    age = 25
}

// with - operate on object
with(person) {
    println("$name is $age years old")
}

Creating DSLs

// HTML builder DSL
html {
    head {
        title { +"Kotlin DSL" }
    }
    body {
        h1 { +"Welcome" }
        p { +"This is a DSL example" }
    }
}

// Database query DSL
val query = query {
    select("name", "age")
    from("users")
    where {
        "age" greaterThan 18
        "name" eq "Alice"
    }
}

Infix Functions

infix fun Int.times(str: String): String {
    return str.repeat(this)
}

println(3 times "Hi ")  // Hi Hi Hi 

// For DSLs
infix fun String.eq(value: Any) {
    // Add to query condition
}
← Back to Tutorials