1. Default values
When you are just starting out, it may seem that the problem “I swapped parameters” is something from the world of big projects. But in practice it appears very early: as soon as you have a function with 3–5 parameters of the same type (for example, several Int or several Boolean), your brain starts tricking you. And it’s not “you’re inattentive”, it’s normal human biology: we don’t have a built-in signature parser.
The solution in Kotlin is simple and effective: some parameters can be made optional via default values, and when calling you can label arguments with names. This turns a function call from a magic spell into a clear phrase you can read like regular text.
Make a parameter optional
Let’s start simple: very often a function is called in the typical way, and only sometimes you want to tweak a detail. For example, “print a header” almost always prints a line of = with the same width — but sometimes you want it wider or with a different character. In such cases, a default value is like a setting you normally don’t need to touch.
The syntax is straightforward: in the parameter declaration write = …. Kotlin uses that value if you don’t pass an argument for this parameter.
fun printHeader(title: String, width: Int = 30, border: Char = '=') {
val line = border.toString().repeat(width)
println(line)
println(title)
println(line)
}
fun main() {
printHeader("錢包") // prints width 30 and '='
printHeader("錢包", width = 10) // prints width 10 and '='
}
Notice an important point: we are not making “two versions” of the function. The function is one, but it has “default settings”. This is almost always better for a project than creating many similar functions with slightly different names.
A default is not only a constant
It might seem that a default value must be something simple like 0, true or "text". But Kotlin allows any expression, including one that depends on other parameters. This is very convenient: for example, “the default length equals the array size”, or “the default limit equals the string length”.
There is only one important rule: if a default depends on another parameter, that “other parameter” must come earlier in the parameter list (logically: you can’t reference something that doesn’t “exist” yet).
A small example from our “Wallet” project: we want to print the list of expenses, and by default print the entire list.
fun printExpenses(amounts: IntArray, size: Int, limit: Int = size) {
var i = 0
while (i < size && i < limit) {
println("Expense #${i + 1}: ${amounts[i]}") // e.g.: Expense #1: 150
i++
}
}
fun main() {
val amounts = intArrayOf(150, 40, 999)
val size = 3
printExpenses(amounts, size) // prints 3 expenses
printExpenses(amounts, size, limit = 1) // prints 1 expense
}
Parameter order: required first, defaulted last
Now an important but logical idea. Default values make a parameter optional — which means you may omit it. Therefore such parameters are always more convenient closer to the end of the list, and required ones closer to the beginning — so the compiler can unambiguously understand which argument you passed where.
Kotlin has a special rule: if a parameter with a default comes before a parameter without a default, then at the call site you can omit that parameter only by using a named argument.
Let’s make an example of “how not to do it”:
fun greeting(userId: Int = 0, message: String) {
println("[$userId] $message")
}
fun main() {
greeting(message = "Hello!") // [0] Hello!
greeting("Hello!") // not allowed: the compiler will complain
}
This order is sometimes necessary (it happens), but more often it’s just a flawed design. In most tasks — and in our app — it’s better to stick to the simple rule: “the most important goes first, the settings go later”.
For example, here is a nicer variant:
fun greeting(message: String, userId: Int = 0) {
println("[$userId] $message")
}
fun main() {
greeting("Hello!") // [0] Hello!
greeting("Hello!", 42) // [42] Hello!
}
2. Named arguments
Label arguments and stop fearing identical types
Named arguments are needed not because Kotlin loves verbosity, but because they dramatically reduce the chance of mistakes — especially when parameters have the same type or when the value itself doesn’t explain the meaning (classic case: a bunch of true, false, true — “what was that?”).
Syntax: at the call site write parameterName = value. Kotlin allows listing named arguments in any order — for readability.
Let’s create a function for adding an expense into arrays (for now without categories, so we don’t jump ahead). Let’s say we have a “date” as day and month — primitive, but perfect for an example.
fun addExpense(
amounts: IntArray,
days: IntArray,
months: IntArray,
size: Int,
amount: Int,
day: Int,
month: Int
): Int {
amounts[size] = amount
days[size] = day
months[size] = month
return size + 1
}
fun main() {
val amounts = IntArray(10)
val days = IntArray(10)
val months = IntArray(10)
var size = 0
size = addExpense(amounts, days, months, size, amount = 150, day = 14, month = 1)
println(size) // 1
}
If we called this positionally as addExpense(…), it would look like a “phone number”. With names, the meaning is immediately visible: amount, day, month.
Change a setting without passing extra stuff
A common scenario: a function has several parameters with defaults, and you want to change not the first of them, but some other one. Kotlin allows this, and it helps to remember a simple rule: if you skip defaulted parameters, then whatever you set after that is usually easier (and safer) to set using named arguments.
The documentation phrases it like this: you can omit some arguments with defaults, but after the first omitted argument you must name all subsequent ones (otherwise it’s unclear what refers to what).
Example: a report printing function. By default we print both the list and the total, and the currency is "EUR". Sometimes you want to change only the currency, without touching the other settings.
fun printReport(
title: String,
showList: Boolean = true,
showTotal: Boolean = true,
currency: String = "EUR"
) {
println("== $title ==")
println("showList=$showList, showTotal=$showTotal, currency=$currency")
}
fun main() {
printReport("Report") // == Report == / showList=true, showTotal=true, currency=EUR
printReport("Report", currency = "USD") // == Report == / showList=true, showTotal=true, currency=USD
}
If named arguments didn’t exist, we would have to write something like printReport("Report", true, true, "USD") — and again guess which two true values were what.
Mix positional and named arguments
In practice you often end up with a “hybrid style”: the first 1–2 parameters are very clear by meaning (usually title, text, amount), so it’s convenient to pass them positionally; after that come settings, and those are better passed as named arguments. Kotlin supports this.
For readability, people usually follow a simple rule: positional arguments first, then named ones. Such a call looks neat — like “main idea + clarifications”.
Let’s apply this to our header:
fun printHeader(title: String, width: Int = 30, border: Char = '=') {
val line = border.toString().repeat(width)
println(line)
println(title)
println(line)
}
fun main() {
printHeader("錢包", border = '#') // title first, then a setting
printHeader("錢包", width = 10, border = '*')
}
This style is especially useful when you design a “mini-API” for yourself: base parameters read quickly, and rare settings don’t get in the way but are always available.
4. Practice: “Wallet” menu
Mini refactor: make the menu extensible
Now let’s assemble a small but complete piece of our console app “Wallet”. We are not adding anything fundamentally new in the logic; we improve the function interface: we add default parameters and use named arguments so that main() reads like a scenario.
We will have a standard menu: show commands, add an expense, show the list, show the report. We still won’t do “perfect input parsing” (that will come in later levels), so we’ll keep it simple: read a line and do basic checks.
fun printMenu(appName: String = "Wallet", showHint: Boolean = true) {
printHeader(appName, width = 25)
println("1) Add expense")
println("2) Show expenses")
println("3) Show total")
println("0) Exit")
if (showHint) println("Enter the command number and press Enter") // Enter the command number...
}
fun printHeader(title: String, width: Int = 30, border: Char = '=') {
val line = border.toString().repeat(width)
println(line)
println(title)
println(line)
}
fun main() {
printMenu() // default name and hint
printMenu(showHint = false) // same screen, but without the hint
printMenu(appName = "Budget v0") // custom name
}
The key idea here: we made the default behavior “typical” for most calls, and moved rare settings into parameters. And thanks to named arguments, printMenu(showHint = false) looks like a readable phrase.
Cheat sheet: defaults and naming
At this point you usually want to ask: “Okay, how do I decide what’s better: a default or naming?” The good news: there are practical criteria. Defaults are a way to make the “common path” shorter, and named arguments are a way to make the “uncommon path” safer and clearer.
| Situation | What to use | Why |
|---|---|---|
| The parameter is almost always the same | Default value | Reduce noise in most calls |
| Several parameters of the same type (Int, Boolean, Char) | Named arguments | Lower the chance of mixing up the order |
| You need to change a “setting at the end” without touching the rest | Defaults + naming the specific setting | No need to pass “extra” arguments |
| The call is hard to read without decoding | Named arguments | The call becomes self-documenting |
And yes, sometimes the right answer is: “the function is overloaded with parameters and should be simplified”. But that’s a sense that comes a bit later, when there are many functions.
Decision scheme: should a parameter have a default?
To reinforce the approach, here is a simple flowchart that is convenient for making this decision in your projects:
flowchart TD
A[There is a function with parameter P] --> B{Is P always required?}
B -->|Yes| C[Keep it without a default]
B -->|No| D{Is there a safe expected value?}
D -->|Yes| E[Make a default: P: Type = ...]
D -->|No| F[Keep it required, but call it named]
E --> G{Same-type parameters and easy to confuse?}
F --> G
G -->|Yes| H[Recommend named arguments]
G -->|No| I[Positional is OK if readable]
The word “safe” is key here. If a default can lead to weird behavior (for example, default month = 0 — but our months start from 1), it’s better to force an explicit value.
5. Common mistakes
Mistake 1: a “just in case” default that looks convenient but breaks the meaning.
Sometimes you want to set a default just to make a parameter optional. For example, set day: Int = 0. But if 0 is an invalid day, you create a time bomb: the program will run, but the data will become garbage. A good default is not “any value”, but an expected and safe one.
Mistake 2: required parameters come after defaulted ones, and calls turn into riddles.
This design forces you to constantly use named arguments even where you wouldn’t want to. Kotlin shows this situation directly: if a default parameter comes before a required one, you can omit it only via a named call. In learning projects it’s almost always easier to reorder the parameters.
Mistake 3: several same-type arguments are passed positionally, and the order gets mixed up.
Three numbers in a row or three boolean flags in a row look the same, and an error in one place is very hard to spot with your eyes. In such calls, named arguments are not “chatter” but insurance.
Mistake 4: chaotic mixing of positional and named arguments.
When some arguments are passed positionally, some are named, and then some are positional again (or just in a weird order), reading becomes painful. Kotlin allows named arguments in any order, but the goal is not to surprise a colleague — it’s to make the code obvious: main part first, then settings.
Mistake 5: too many parameters with defaults as an attempt to replace proper design.
If a function has 8 parameters, 6 of them with defaults, and you don’t remember what each means — it’s a signal the function does too much. In this course we won’t dive into advanced constructs yet, but at minimum it’s worth stopping and asking yourself: “Can I split the action into two simpler functions?”
GO TO FULL VERSION