Explain it simply
Explain it simply
Think of a function as a recipe with a name. You hand over the ingredients (the parameters), the steps run, and a dish (the return value) comes back. The recipe is written once and can be used by name whenever you need it. In Kotlin you declare a function with the fun keyword.
A good function does one job and its name tells you which. That way main() stops being a heap of details and becomes a readable story made of names such as calculateTotal() and greet(). Kotlin's default and named arguments make the calls read almost like sentences too.
Problem → Why → Solution
The problem: copied logic that one place forgot to update
A small shop's receipt multiplies a price by a quantity and adds 5% tax. The calculation is copied for the first two items and pasted again for the third. Next month the tax becomes 8%, someone edits only one of the three lines and forgets the rest. Some receipts are now wrong, and the program gives no error at all.
fun main() {
val breadTotal = 3 * 1200 + 3 * 1200 * 5 / 100
val riceTotal = 2 * 2500 + 2 * 2500 * 5 / 100
val teaTotal = 5 * 800 + 5 * 800 * 8 / 100 // only this line got the new rate
println(breadTotal + riceTotal + teaTotal)
}Why does a function solve this?
Logic written in three places means three places to edit and one to forget. Put it in a single named function and there is only one place to change. On top of that the compiler checks the function's signature (parameter types and return type), so a wrong argument is caught at every call site immediately.
Core concept: signature, return and arguments
You declare a function as fun name(parameter: Type): ReturnType { body }. Every parameter must have a type, and the return type comes after a : following the closing parenthesis. Parameters are read-only inside the body: writing count++ gives the error 'val' cannot be reassigned. If you need a changing value, take your own var copy inside the body.
A function with a { } body must contain its own return, and the value's type must match the declared one. fun total(a: Int, b: Int): String { return a + b } is rejected with: return type mismatch: expected 'String', actual 'Int'. Forget the return and you get: missing return statement. One-line functions can be written with = as in fun double(x: Int) = x * 2 (a single-expression function), and the compiler infers the return type. For functions used from other files, writing the return type out still helps readers.
Functions that return nothing useful, such as one that only prints, return Unit. It plays the role of void in Java, but it is a real type, so you can leave the return type off (fun log(message: String) { ... }). Writing val r: Unit = log("done") and printing r gives kotlin.Unit.
A default argument (day: String = "Sunday") is used when the caller leaves that argument out. The default expression is evaluated on every call, and only when it is needed. A named argument (greet(day = "Friday", name = "Su")) says which value is which, lets you reorder them, and protects you from swapping two parameters of the same type.
| Feature | Syntax | What it is for |
|---|---|---|
| Default argument | x: Int = 1 | A value used when the caller omits it |
| Named argument | f(x = 2) | Clear calls in any order |
| vararg | vararg xs: Int | Accept any number of arguments |
| Single expression | fun f(x: Int) = x * 2 | A one-line function |
- The caller passes arguments in
- Parameters become read-only names
- The body computes the result
- return hands one value back
Defaults fill in what the caller leaves out, and named arguments say which value is which.
General pattern
fun name(param: Type, optional: Type = defaultValue): ReturnType {
return value
}
fun name(param: Type): ReturnType = expression
fun name(vararg items: Type) { /* items behaves like an array */ }The first form has a block body and a return, the second is a one-line function with =, and the third accepts any number of arguments through vararg. When nothing useful is returned you can omit : ReturnType (it is Unit).
Example: greet() with a default and named arguments
greet() takes a name and a day and returns a one-line greeting. When day is omitted it uses "Sunday". main() calls it three ways: relying on the default, passing both values by position, and passing them by name in a different order.
fun greet(name: String, day: String = "Sunday"): String {
return "Hello $name, today is $day."
}
fun main() {
println(greet("Aung"))
println(greet("Hla", "Monday"))
println(greet(day = "Friday", name = "Su"))
}Code breakdown
- Signature
fun greet(name: String, day: String = "Sunday"): String {fun, the name, two typed parameters, a default value for day, and : String as the return type. This single line tells you how to call the function.
- return
return "Hello $name, today is $day."A string template puts both parameters into the text and returns it. The result is a String, matching the declared type.
- Default used
println(greet("Aung"))day is not supplied, so the default "Sunday" is used and the output is "Hello Aung, today is Sunday."
- Positional arguments
println(greet("Hla", "Monday"))Both arguments are given in the parameter order: the first is name, the second is day. The default is not used.
- Named arguments
println(greet(day = "Friday", name = "Su"))Naming the arguments lets you change the order and tells the reader which is which. It also prevents the bug of swapping two Strings.
Hello Aung, today is Sunday.
Hello Hla, today is Monday.
Hello Su, today is Friday.- name is set to "Aung"
- day is missing, so the default is used
- The body builds the string template
- return sends the text back to main
Argument supplied
Use the caller's value
Argument omitted
Evaluate and use the default
One-liners, Unit, and defaults evaluated on every call
double and isAdult are single-expression functions whose types the compiler infers. log() returns Unit and gives level a default. The default of record()'s id parameter calls nextId(), which shows that a default is not a constant but an expression evaluated per call. If id is supplied directly, nextId() is not called at all.
var counter = 0
fun nextId(): Int {
counter++
return counter
}
fun double(x: Int) = x * 2
fun isAdult(age: Int) = age >= 18
fun log(message: String, level: String = "INFO") {
println("[$level] $message")
}
fun record(name: String, id: Int = nextId()) = "$id:$name"
fun main() {
println(double(21))
println(isAdult(17))
log("started")
log("disk almost full", level = "WARN")
println(record("a"))
println(record("b"))
println(record("c", id = 99))
println(record("d"))
println("calls to nextId: $counter")
val result: Unit = log("done")
println(result)
}The output is 42, false, [INFO] started, [WARN] disk almost full, 1:a, 2:b, 99:c, 3:d, calls to nextId: 3, [INFO] done and kotlin.Unit. In record("c", id = 99) nextId() is not called, so record("d") receives 3, not 4. That proves defaults are evaluated per call and only when needed.
vararg, spread and local functions
A vararg parameter behaves like an array inside the function. Callers may pass any number of arguments, including none (total() is 0). If you already have an array, spread it with the * operator, as in total(*prices); you can mix in other arguments before and after it. The rule() inside report() is a local function: it is visible only inside report and reads title straight from the surrounding scope.
fun total(vararg amounts: Int): Int {
var sum = 0
for (amount in amounts) sum += amount
return sum
}
fun report(title: String, vararg lines: String) {
fun rule() = println("-".repeat(title.length))
println(title)
rule()
for (line in lines) println(line)
rule()
}
fun main() {
println(total())
println(total(5, 10, 15))
val prices = intArrayOf(100, 200, 300)
println(total(*prices))
println(total(1, *prices, 9))
report("Daily sales", "Tea: 1600", "Rice: 2500")
}The output is 0, 30, 600, 610, then the title Daily sales, a rule of 11 dashes (the length of the title), the two lines, and a second rule. Because rule() is declared inside report, nothing outside can use it, so it adds nothing to the surrounding namespace.
In real projects
Where this shows up in real projects
Production Kotlin code is built from lots of small functions: calculateShipping(weightKg, zone), isValidEmail(text), formatPrice(amount, currency = "MMK"), where the name alone says what happens. Default and named arguments let a function with many options, such as an HTTP client call with a timeout, retries and headers, be offered without writing a pile of overloads.
Teams read a function signature as an API, so parameter order, names and types are chosen with care. A call such as createUser("Aye", true, false) with two booleans in a row is a puzzle for the reader, while createUser("Aye", admin = true, active = false) is clear. Keeping each function to one job and small enough to read on a single screen makes it easy to unit test and makes mistakes visible in code review.
Common mistakes
Common mistakes
1. Swapping two arguments of the same type
greet("Monday", "Aung") compiles because both are Strings, and prints the nonsense "Hello Monday, today is Aung." with no error. When parameters share a type, call with names: greet(name = "Aung", day = "Monday").
2. A missing return, or one of the wrong type
fun total(a: Int, b: Int): Int { a + b } fails with: missing return statement. Declaring String and then writing return a + b fails with: return type mismatch: expected 'String', actual 'Int'. The = form (fun total(a: Int, b: Int) = a + b) cannot produce either mistake.
3. Trying to modify a parameter
fun bump(count: Int) { count++ } fails with: 'val' cannot be reassigned. Parameters are vals. Take a local copy with var current = count and change that, or simply return the new value.
4. Misusing vararg
Calling fun total(vararg amounts: Int) with an array, as in total(prices), gives: argument type mismatch: actual type is 'IntArray', but 'Int' was expected. Write total(*prices). When a parameter follows a vararg (fun log(vararg parts: String, level: Int)), it can only be passed by name: log("a", "b", 3) does not compile, log("a", "b", level = 3) does.
Best practices
Best practices
- Give each function one job and start its name with a verb (calculateTotal, isValid).
- Use named arguments when two parameters share a type or when a call passes a Boolean.
- Write the return type on public functions used from other files; for tiny local helpers a single-expression body with inference is fine.
Mini challenge
Mini challenge: a trip log
Write functions that summarise each trip in one line. Use a default parameter, named arguments, a single-expression function, a vararg and a local function at least once each.
- Write averageSpeed(distanceKm, minutes) as a single-expression function (distanceKm * 60 / minutes, integer)
- describeTrip(distanceKm, minutes, label = "Trip") returns a line like "Trip: 01h15m, 72 km/h"
- Inside describeTrip declare a local function twoDigits that pads a number to two digits, such as 01
- longestTrip(vararg distances: Int) returns the largest distance
- In main call describeTrip once with named arguments and once with the label by position, and print longestTrip's result too
fun averageSpeed(distanceKm: Int, minutes: Int): Int {
// TODO: make this a single-expression function with =
}
fun describeTrip(distanceKm: Int, minutes: Int, label: String = "Trip"): String {
// TODO: local fun twoDigits(n: Int) that returns "05" for 5 and "12" for 12
// TODO: hours = minutes / 60 and rest = minutes % 60
// TODO: return text such as "Trip: 01h15m, 72 km/h"
}
fun longestTrip(/* TODO: vararg distances */): Int {
// TODO: loop and keep the largest value
}
fun main() {
// TODO: describeTrip(90, 75) with names, then describeTrip(30, 45, "Commute")
// TODO: print longestTrip(90, 30, 120, 45)
}Expected: The program should print: Trip: 01h15m, 72 km/h Commute: 00h45m, 40 km/h 120
Show hint
Declare twoDigits at the top of describeTrip's body as fun twoDigits(n: Int) = if (n < 10) "0$n" else "$n". A vararg parameter is an array inside the function, so for (d in distances) works. 90 km in 75 minutes is 90 * 60 / 75 = 72.
Show solution
fun averageSpeed(distanceKm: Int, minutes: Int): Int = distanceKm * 60 / minutes
fun describeTrip(distanceKm: Int, minutes: Int, label: String = "Trip"): String {
fun twoDigits(n: Int) = if (n < 10) "0$n" else "$n"
val hours = minutes / 60
val rest = minutes % 60
val time = "${twoDigits(hours)}h${twoDigits(rest)}m"
return "$label: $time, ${averageSpeed(distanceKm, minutes)} km/h"
}
fun longestTrip(vararg distances: Int): Int {
var best = 0
for (distance in distances) {
if (distance > best) best = distance
}
return best
}
fun main() {
println(describeTrip(distanceKm = 90, minutes = 75))
println(describeTrip(30, 45, "Commute"))
println(longestTrip(90, 30, 120, 45))
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- In fun name(param: Type): ReturnType every parameter has a type and is a read-only val in the body.
- Use = for single-expression functions with inferred return types; a function that returns nothing useful returns Unit.
- Defaults are evaluated per call and only when needed, and named arguments make calls clear and stop same-typed parameters being swapped.
- A vararg arrives as an array and an existing array is passed with *; a local function keeps a helper inside its only user.
Kotlin language guide — Kotlin