Kotlin: Functions – code examples
Contents
Function with Default Value
Use case: Bundle recurring logic, e.g. greeting texts or calculations.
fun begruesse(name: String, gruss: String = "Hello") = "$gruss, $name!"
fun main() {
println(begruesse("Ada"))
println(begruesse("Linus", gruss = "Hi"))
}Default values and named arguments usually make overloads unnecessary. Output: Hello, Ada! and Hi, Linus!.
Extension Functions
Functions#extension#string#list
Use case: Add your own helper functions to existing types (String, List).
fun String.istPalindrom(): Boolean {
val t = lowercase()
return t == t.reversed()
}
fun List<Int>.durchschnitt(): Double =
if (isEmpty()) 0.0 else sum().toDouble() / size
fun main() {
println("Anna".istPalindrom())
println("Kotlin".istPalindrom())
println(listOf(1, 2, 3, 4).durchschnitt())
}Extension functions read like methods but are resolved statically and do not modify the class. Output: true, false, 2.5.
Scope Functions
Functions#apply#let#also#scope
Use case: Configure objects, process nullable values, and slip in debug output.
class Konfig {
var host = ""
var port = 0
}
fun main() {
val k = Konfig().apply {
host = "localhost"
port = 8080
}
println("${k.host}:${k.port}")
val laenge = "Kotlin".also { println("Value: $it") }.length
println(laenge)
println("42".toIntOrNull()?.let { it * 2 })
}apply configures an object (this) and returns it, also handles side effects (it), let transforms. Output: localhost:8080, Value: Kotlin, 6, 84.
Lambdas and Higher-Order Functions
Functions#lambda#higher-order#function-type
Use case: Pass behavior as a parameter, e.g. callbacks, sorting, or filtering logic.
val addiere: (Int, Int) -> Int = { a, b -> a + b }
fun anwenden(x: Int, y: Int, op: (Int, Int) -> Int) = op(x, y)
fun <T> wiederhole(n: Int, aktion: (Int) -> T): List<T> = (1..n).map(aktion)
fun main() {
println(anwenden(3, 4, addiere))
println(anwenden(3, 4) { a, b -> a * b })
println(wiederhole(3) { it * 10 })
}Functions are values; the last lambda argument goes after the parentheses. Output: 7, 12, [10, 20, 30].