KtKotlin
IntermediateLesson 10 of 16

Extension Functions, Lambdas & Scope Functions – Kotlin

Extending existing types and using functions as values.

With an extension function, you add functions to foreign classes without modifying them or inheriting from them. Inside the function, this is the object (it can usually be omitted).

fun String.istPalindrom(): Boolean {
    val t = lowercase()
    return t == t.reversed()
}

val String.wortAnzahl: Int                      // extension property
    get() = trim().split(Regex("\\s+")).size

println("Anna".istPalindrom())                  // true
println("Kotlin is great".wortAnzahl)           // 3

Lambdas are functions as values: { x: Int -> x * 2 }. If a lambda has a single parameter, it is called it. If the lambda is the last argument, it goes after the parentheses (trailing lambda) – hence the familiar map { } syntax.

val doppelt = { x: Int -> x * 2 }
println(doppelt(21))                              // 42

val zahlen = listOf(1, 2, 3, 4)
println(zahlen.map { it * it })                   // [1, 4, 9, 16]
println(zahlen.filter { it % 2 == 0 })            // [2, 4]
println(zahlen.fold(0) { summe, x -> summe + x }) // 10

fun anwenden(x: Int, f: (Int) -> Int) = f(x)      // higher-order function
println(anwenden(5) { it + 1 })                   // 6

Scope functions (let, run, with, apply, also) execute a block of code in the context of an object. They differ in whether the object is available as it or this and in what is returned:

  • let: object as it, returns the lambda result (ideal with ?.let { } for nullable values)
  • run / with: object as this, returns the lambda result
  • apply: object as this, returns the object itself (configuring)
  • also: object as it, returns the object itself (side effects such as logging)
class Konfig { var host = ""; var port = 0 }

val k = Konfig().apply {
    host = "localhost"
    port = 8080
}
println("${k.host}:${k.port}")                       // localhost:8080
val info = with(k) { "$host on port $port" }         // localhost on port 8080
val zahl = "42".toIntOrNull()?.let { it * 2 }      // 84
"Value".also { println("Debug: $it") }              // Debug: Value
WarningDo not overdo nested scope functions – it quickly becomes unclear what this and it refer to. Two levels are usually the limit.