Functions, Default and Named Arguments
Declaring functions in Kotlin, and the default/named argument features that eliminate most overload boilerplate.
2 min read
A basic Kotlin function looks like this:
fun greet(name: String): String {
return "Hello, $name!"
}
println(greet("Alice")) // Hello, Alice!fun declares the function, parameters are typed like variables, and the return type follows a colon after the parameter list. If a function returns nothing meaningful, its return type is Unit (roughly Kotlin's equivalent of void), and it can be omitted entirely:
fun logMessage(message: String) {
println("[LOG] $message")
}Default arguments
Parameters can declare a default value, making them optional at the call site:
fun greet(name: String, greeting: String = "Hello"): String {
return "$greeting, $name!"
}
println(greet("Alice")) // Hello, Alice!
println(greet("Alice", "Welcome")) // Welcome, Alice!In Java, supporting this kind of optional parameter usually means writing several overloaded versions of the same method that just forward to each other. Kotlin's default arguments replace all of those overloads with one function declaration — there's exactly one place to read and update the logic.
Named arguments
You can pass arguments by parameter name instead of position, in any order:
fun createUser(name: String, age: Int = 18, isAdmin: Boolean = false) {
println("$name, age $age, admin=$isAdmin")
}
createUser(name = "Alice", isAdmin = true)
createUser("Bob", isAdmin = true, age = 25)This matters most once a function has several parameters, especially several of the same type — createUser("Alice", 25, true) forces a reader to remember what each position means, while createUser(name = "Alice", age = 25, isAdmin = true) is unambiguous at the call site, with no need to check the function's signature to understand it.
Combining both
Default and named arguments together mean callers can skip any parameter that has a sensible default and set only the ones that matter for a given call:
fun sendEmail(
to: String,
subject: String = "(no subject)",
cc: String? = null,
urgent: Boolean = false
) {
println("To: $to | Subject: $subject | CC: $cc | Urgent: $urgent")
}
sendEmail(to = "team@example.com")
sendEmail(to = "team@example.com", urgent = true)
sendEmail(to = "team@example.com", cc = "boss@example.com", subject = "Q3 Report")Every one of these calls is valid, and each reads clearly without needing to pass values for parameters that don't apply.
Varargs
A parameter marked vararg accepts any number of arguments, collected into an array inside the function:
fun sum(vararg numbers: Int): Int {
return numbers.sum()
}
println(sum(1, 2, 3, 4)) // 10Functions are where a lot of Kotlin's day-to-day conciseness comes from. The next lesson looks at single-expression functions — a shorthand for functions whose entire body is one expression.