Functions and Lambdas
Functions
kotlin
fun greet(name: String): String {
return "Hello, $name!"
}
fun square(x: Int) = x * x // single-expression function
fun printLine(text: String): Unit { // Unit means "nothing useful returned"
println(text)
}
Default and Named Arguments
kotlin
fun makeCoffee(size: String = "medium", sugar: Int = 1) = "A $size coffee with $sugar sugar"
println(makeCoffee())
println(makeCoffee(sugar = 0)) // named argument
println(makeCoffee(size = "large", sugar = 2))
Why this matters: Jetpack Compose functions have many parameters with defaults, such as
Text(text = "Hi", color = Color.Red). Named arguments make them easy to read.
Lambdas
A lambda is a small function without a name that you can store or pass around.
kotlin
val double = { x: Int -> x * 2 }
println(double(5)) // 10
val numbers = listOf(5, 3, 8, 1)
println(numbers.map { it * 2 }) // [10, 6, 16, 2] (it = the single parameter)
println(numbers.filter { it > 3 }) // [5, 8]
println(numbers.sortedDescending()) // [8, 5, 3, 1]
println(numbers.sumOf { it }) // 17
Higher-Order Functions
kotlin
fun perform(action: () -> Unit) {
println("Before")
action()
println("After")
}
perform { println("Doing work") } // trailing lambda syntax
fun calculate(a: Int, b: Int, op: (Int, Int) -> Int) = op(a, b)
println(calculate(4, 5) { x, y -> x * y }) // 20
You use this style constantly in Compose: Button(onClick = { ... }) { Text("Tap") }.
Scope Functions
| Function | Object is | Returns | Good for |
|---|---|---|---|
let | it | Lambda result | Run code if not null |
apply | this | The object | Configure an object |
also | it | The object | Side effects like logging |
run | this | Lambda result | Compute with the object |
with | this | Lambda result | Many calls on one object |
kotlin
val user: String? = "Asha"
user?.let { println("Hello $it") }
val intent = Intent().apply {
action = Intent.ACTION_SEND
type = "text/plain"
}
Extension Functions
kotlin
fun String.isValidEmail(): Boolean = contains("@") && contains(".")
println("asha@mail.com".isValidEmail()) // true
Conclusion
Functions with defaults and names read naturally, and lambdas power collections and Compose. Learn trailing lambdas and scope functions.
Quick Summary: Default and named arguments, lambdas with it, trailing lambda syntax, scope functions and extension functions.

