Generics, Delegation & DSLs – Kotlin
Variance, reified, delegated properties, class delegation, and builder DSLs.
Generics work as in Java, but instead of wildcards Kotlin uses declaration-site variance: out T (producer, covariant) and in T (consumer, contravariant). That is why List<String> is a List<Any> – List<out E> is read-only.
fun <T : Comparable<T>> maximum(liste: List<T>): T {
var max = liste.first()
for (x in liste) if (x > max) max = x
return max
}
println(maximum(listOf(3, 9, 4))) // 9
println(maximum(listOf("pear", "apple"))) // pear
interface Quelle<out T> { fun hole(): T } // only returns T
interface Ziel<in T> { fun nimm(x: T) } // only accepts T
val strings: List<String> = listOf("a")
val anys: List<Any> = strings // allowed thanks to outNormally, type parameters are erased at runtime (type erasure). With inline functions using reified, the type is preserved so that you can use is T or as? T:
inline fun <reified T> Any?.alsTyp(): T? = this as? T
println("Text".alsTyp<String>()) // Text
println("Text".alsTyp<Int>()) // null
inline fun <reified T> List<*>.nurTyp(): List<T> = filterIsInstance<T>()
println(listOf(1, "two", 3).nurTyp<Int>()) // [1, 3]Delegation is built into Kotlin. For classes, by forwards all interface methods to another object (composition instead of inheritance). For properties, a delegate takes over the behavior: lazy (compute on first access), Delegates.observable (react to changes).
interface Drucker { fun drucke(text: String) }
class KonsolenDrucker : Drucker {
override fun drucke(text: String) = println("> $text")
}
class MeinDrucker(d: Drucker) : Drucker by d {
fun doppelt(text: String) { drucke(text); drucke(text) }
}
MeinDrucker(KonsolenDrucker()).doppelt("Hi") // > Hi (twice)
class Einstellungen {
val teuer: String by lazy { println("computing..."); "Result" }
var lautstaerke: Int by kotlin.properties.Delegates.observable(5) { _, alt, neu ->
println("Volume: $alt -> $neu")
}
}Functions with a receiver (Html.() -> Unit) enable type-safe builder DSLs – this is how Gradle Kotlin scripts, Ktor routing, or Jetpack Compose work. With operator you overload operators:
class Html {
val zeilen = mutableListOf<String>()
fun p(text: String) { zeilen += "<p>$text</p>" }
}
fun html(block: Html.() -> Unit): String = Html().apply(block).zeilen.joinToString("\n")
println(html {
p("Hello")
p("World")
})
data class Vec(val x: Int, val y: Int) {
operator fun plus(o: Vec) = Vec(x + o.x, y + o.y)
operator fun times(k: Int) = Vec(x * k, y * k)
}
println(Vec(1, 2) + Vec(3, 4)) // Vec(x=4, y=6)
println(Vec(1, 2) * 3) // Vec(x=3, y=6)by is Kotlin's answer to "inheritance vs. composition": you do not inherit behavior, you delegate it. This saves boilerplate forwarding methods.