Functions, Default Arguments, Lambdas, and Extension Functions
Move from simple statements to reusable logic with functions, named arguments, higher-order functions, lambdas, and one of Kotlin’s signature features: extension functions.
Inside this chapter
- Basic Functions
- Default and Named Arguments
- Lambdas and Higher-Order Functions
- Extension Functions
- Single-Expression Functions
- Real-Time Example
Series navigation
Study the chapters in order for the clearest path from Kotlin setup and syntax to coroutines, backend work, clean design, multiplatform thinking, and advanced engineering practice. Use the navigation at the bottom to move smoothly through the full tutorial series.
Basic Functions
fun add(a: Int, b: Int): Int {
return a + b
}
Functions are the first step toward clean program structure. They help isolate logic, improve readability, and make testing easier.
Default and Named Arguments
fun greet(name: String, prefix: String = "Hello"): String {
return "$prefix, $name"
}
println(greet(name = "Anita"))
println(greet(name = "Anita", prefix = "Welcome"))
This feature reduces overloaded method clutter and makes call sites clearer.
Lambdas and Higher-Order Functions
val numbers = listOf(1, 2, 3, 4)
val doubled = numbers.map { it * 2 }
Kotlin uses higher-order functions heavily, especially in collections APIs, asynchronous callbacks, builders, and DSL design.
Extension Functions
fun String.initials(): String {
return split(" ")
.filter { it.isNotBlank() }
.joinToString("") { it.first().uppercase() }
}
println("Riya Sen".initials())
Extension functions allow developers to add utility behavior in a natural way without modifying the original class source. They are common in Android utilities, backend helper modules, and reusable libraries.
Single-Expression Functions
fun square(x: Int) = x * x
This syntax keeps simple logic concise and readable.
Real-Time Example
In an online booking platform, functions may validate traveler details, compute fare breakdowns, format itinerary data, and trigger downstream calls. Strong function design prevents business logic from turning into a long unreadable block.