Functions and Lambdas
Declaring functions
fun greet(name: String, greeting: String = "Hello"): String {
return "$greeting, $name!"
}
greet("Ada") // "Hello, Ada!" (uses the default)
greet("Ada", "Welcome") // "Welcome, Ada!" (positional)
greet(name = "Ada", greeting = "Hi") // "Hi, Ada!" (named, order doesn't matter)
greeting: String = "Hello" is a default argument, callers can skip it entirely. Named arguments let you pass values by parameter name, useful when a function takes several similarly-typed parameters and you want the call site to stay readable.
Single-expression functions
When a function's body is just one expression, you can skip return and the braces entirely:
fun square(x: Int) = x * x
Lambdas and higher-order functions
A lambda is a function value, one you can store in a variable or pass as an argument:
val double: (Int) -> Int = { x -> x * 2 }
println(double(5)) // 10
A function that accepts another function as a parameter is a higher-order function:
fun applyTwice(x: Int, op: (Int) -> Int): Int = op(op(x))
println(applyTwice(3) { it + 1 }) // 5
Two things happening in that last line:
- When a lambda is the last parameter, it can be written outside the parentheses, this is called trailing lambda syntax, and it's everywhere in idiomatic Kotlin.
- Inside a single-parameter lambda,
itis the implicit name for that parameter, so{ it + 1 }means "take the one argument and add 1", no need to write{ x -> x + 1 }when there's nothing ambiguous about it.