Functions, Lambdas & Higher-Order Functions
Functions
fun add(a: Int, b: Int): Int = a + b // single-expression
fun greet(name: String = "friend") = "Hi $name" // default argument
fun area(w: Int, h: Int) = w * h
area(h = 3, w = 4) // named arguments
Lambdas
val square = { x: Int -> x * x }
println(square(5)) // 25
Higher-order functions
A function that takes or returns another function:
fun repeatAction(times: Int, action: (Int) -> Unit) {
for (i in 0 until times) action(i)
}
repeatAction(3) { println("Run #$it") }
Extension functions
fun String.shout() = this.uppercase() + "!"
println("hi".shout()) // HI!
Tip: it is the implicit name of a single lambda parameter — handy but name it when there are several.