Kotlin Functions

Functions are concise in Kotlin and can be highly expressive. Default values and named arguments reduce overload noise.

Parameters

Function parameters in Kotlin are read-only (val) by default and can declare default values directly in the signature. Default parameters eliminate the need to write multiple telescoping overloads just to provide sensible fallbacks:

fun greet(name: String, title: String = "developer") {
    println("$name is a $title")
}

// Callers can omit `title` to use the default
greet("Ada")

Named arguments

Named arguments let callers bind parameters by name in any order, which prevents silent positional swaps when a function takes several Boolean or String flags:

fun connect(host: String, port: Int = 5432, useTls: Boolean = true) {
    println("Connecting to $host:$port (tls=$useTls)")
}

// Self-documenting call site; order no longer depends on signature position
connect(useTls = false, host = "localhost")

Lambdas

Kotlin treats functions as first-class values. A lambda expression sits inside curly braces { params -> body }, and when a lambda is the last parameter of a function, Kotlin lets you move it outside the parentheses (trailing lambda syntax), which powers collection pipelines and DSLs:

val sum: (Int, Int) -> Int = { a, b -> a + b }
val items = listOf(1, 2, 3, 4)

// Trailing lambda with implicit `it` parameter for single-arg lambdas
val evens = items.filter { it % 2 == 0 }
println("sum=${sum(2, 3)}, evens=$evens")

Extension functions

Extension functions add utility methods to existing classes—even final JDK types like String—without inheritance or wrapper classes. Note that extensions are resolved statically by the declared variable type, not dynamically via virtual dispatch:

fun String.slugify(): String =
    this.trim().lowercase().replace(Regex("\\s+"), "-")

println("Kotlin Functions".slugify()) // "kotlin-functions"

Practice

Build fluency with Kotlin signatures and higher-order functions:

  1. Write a formatPrice(amount: Double, currency: String = "USD", includeTax: Boolean = false) function and call it with named arguments.
  2. Pass a trailing lambda to listOf(...).map { ... } to transform a list of strings.
  3. Write an extension function on Int (for example, fun Int.isEven() = this % 2 == 0) and test it.