Functions, Default Arguments, and Lambdas
Function declarations, default/named arguments, and higher-order functions with lambdas.
What you'll learn
- Declare a function with default argument values and call it with named arguments
- Write a single-expression function using = instead of a block body
- Pass a lambda to a higher-order function like a collection's map or filter
Explanation
Kotlin functions can declare default argument values: fun greet(name: String, greeting: String = "Hello") { println("$greeting, $name!") } -- calling greet("Ada") uses the default greeting, while greet("Ada", "Hi") overrides it. Combined with named arguments (greet(name = "Ada", greeting = "Hi")), this often eliminates the need for function overloading that other languages rely on default values or overloads for.
A function whose body is a single expression can use = instead of a block with return: fun square(n: Int) = n * n is equivalent to fun square(n: Int): Int { return n * n }, but more concise.
Kotlin treats functions as values, enabling higher-order functions -- functions that take other functions (often written as lambdas) as arguments. A lambda is written in curly braces: { x -> x * 2 }. Collection functions like map and filter take a lambda: listOf(1, 2, 3).map { it * 2 } produces [2, 4, 6] -- note it is the implicit name for a lambda's single parameter when you don't name one explicitly.
Guided lab
Predict: Default arguments and a map lambda
Read this program and predict exactly what it prints.
fun greet(name: String, greeting: String = "Hello") = "$greeting, $name!"
fun main() {
println(greet("Ada"))
println(greet("Grace", "Hi"))
val doubled = listOf(1, 2, 3).map { it * 2 }
println(doubled)
}Stuck? Get a hint.
Common mistakes
- Forgetting that named arguments let you skip earlier default-valued parameters and only override a later one.
- Writing an unnecessarily verbose block-body function when a single-expression function (using =) would be clearer.
- Confusing `it` (the implicit lambda parameter) with a named variable when a lambda genuinely needs an explicit parameter name for clarity.
Knowledge check
Takeaway
Default and named arguments reduce the need for overloads; single-expression functions (=) and lambdas (with implicit `it`) keep code concise.
Summary
Functions can have default/named arguments and single-expression bodies; higher-order functions accept lambdas, with `it` as the implicit single-parameter name.
References
Your notes
Notes save automatically.
Finished this lesson?
Mark it complete to track your progress and schedule a future review.
AI tutor
The optional AI tutor isn't enabled in this deployment. All lessons, exercises, quizzes, and search work fully without it.