1. Declaring functions
When you’re just starting to program, it feels like the simplest option is to write all the code in main, top to bottom. And that’s perfectly fine at the first steps: your brain is busy with syntax rather than architecture.
But pretty quickly two symptoms appear: you copy the same pieces of code (and then fix bugs in five places), and main turns into a huge “sheet” of code you’re afraid to touch. Functions are a way to give a name to a repeated action or computation so the code reads like a script: “first ask for input, then calculate, then print”.
Imagine that a program is a recipe. main is “what we do step by step”, and functions are “how exactly to chop an onion” and “how to boil pasta”.
Minimal function: fun name() { ... }
First, let’s look at the simplest kind of function: no parameters and no result. In Kotlin, a function is created using the keyword fun, then the name and parentheses with parameters (empty for now), and then the body in curly braces.
Important: functions (like main) are usually declared at the file level, meaning not “inside main”. We’ll cover local functions later, but for now we’ll stick to the classic approach: functions separately, main separately.
fun printWelcome() {
println("Welcome to the program!") // Welcome to the program!
}
fun main() {
printWelcome()
println("We’ll start working now...") // We’ll start working now...
}
Here printWelcome() is simply a “command”. We called it, and it executed. Notice two things.
First, the function declaration by itself doesn’t start anything. Until you call printWelcome() from main, the program doesn’t even have to “remember” that such a function exists.
Second, a function name is not the place for fantasy. Good names start with an action: printWelcome, readAge, calculateTotal. With them, code starts to read almost like plain text.
Parameters and arguments
Almost immediately you want a function that can work with different data. That’s what parameters are for.
Parameters are variables a function receives as input. They are declared in parentheses and must have a type. Arguments are the concrete values you pass when calling the function.
Let me put these facts into a small table:
| Term | Where it lives | Example | How to understand it |
|---|---|---|---|
| Parameter | in the function declaration | |
“what the function expects as input” |
| Argument | in the function call | |
“what you actually passed” |
Now an example. Let’s make a function that prints a greeting for a specific user:
fun greet(name: String) {
println("Hi, $name!") // Hi, Kotlin!
}
fun main() {
greet("Kotlin")
greet("world")
}
Here name: String is a parameter, and "Kotlin" and "world" are arguments. Note: the parameter name is available only inside the function body. The function ends, and the parameter disappears.
Functions with multiple parameters
When there are multiple parameters, they’re separated by commas. And this is where the first “human” errors show up: mixing up the order of arguments is easier than it seems (especially if the types are the same, for example two Int values).
Let’s make a function that prints a “frame” for a title. It looks like a small thing, but such small things train your brain well: you immediately see the benefit of “giving a name to a repeated piece of code”.
fun printTitle(title: String, width: Int) {
println("=".repeat(width))
println(title)
println("=".repeat(width))
}
fun main() {
printTitle("Report", 10)
}
If you accidentally called printTitle(10, "Report"), the compiler wouldn’t let the program compile because the types don’t match (and that’s good). But if it were printTitle(width: Int, height: Int) the compiler would accept it, and the logic would break. That’s why meaningful parameter names are not just aesthetics, but also protection against mistakes.
2. Return values and signatures
Return type: a function as an “expression”, not just an “action”
So far we’ve made functions that print something. But very often a function must calculate and return the result back. Then we say that the function “returns a value”.
In Kotlin, the return type is written after the parameter list using a colon: : Int, : String, : Boolean, and so on. A basic Kotlin syntax example shows the function sum(a: Int, b: Int): Int that returns the sum.
fun sum(a: Int, b: Int): Int {
return a + b
}
fun main() {
val total = sum(10, 20)
println(total) // 30
}
Try not to be scared by the word return: in the next lecture we’ll look at how exactly a function “finishes” and what it means to “return a value”. For now, fix the main idea: if a function has the return type : Int, then the call result can be assigned to a variable and used later.
An important observation: calling a function that returns a value is an expression. That means you can substitute it inside a string or another computation.
fun sum(a: Int, b: Int): Int {
return a + b
}
fun main() {
println("2 + 3 = ${sum(2, 3)}") // 2 + 3 = 5
}
We literally inserted the result of the function into a string template. You already know how to do this with variables; now you’re learning to do it with functions.
Function signature as a contract
When you see a function, it’s useful to read its header as a contract. This helps a lot when code gets bigger and you no longer remember what is written where.
Let’s take an example:
fun average(total: Int, days: Int): Double {
return total.toDouble() / days
}
Its signature is:
- name: average
- parameters: (total: Int, days: Int)
- return type: Double
And that’s almost everything you need to use the function. Even without reading the body, you can understand: “give me total and days, I’ll return a Double”.
You can imagine it as a small diagram:
flowchart LR
A["Arguments in the call<br/>average(7000, 7)"] --> B["Function parameters<br/>total: Int, days: Int"]
B --> C["Function body<br/>calculations"]
C --> D["Call result<br/>Double"]
If you can read signatures, you start programming faster: you jump around files less, rely less on intuition, and rely more on the contract.
Parameters inside a function are read-only
Beginners often want to do this: “I received a parameter, now I’ll tweak it and return it.” But Kotlin doesn’t allow reassigning parameters. This is intentional: parameters are input data, not working variables. Treat them like val variables. That’s exactly how the Kotlin compiler treats them.
So you can’t do this (the compiler will complain):
fun makeLouder(text: String): String {
text = text.uppercase() // Compilation error: Val cannot be reassigned
return text.uppercase()
}
If you need to change something, create a local variable:
fun normalizeName(name: String): String {
var result = name.trim()
result = result.replaceFirstChar { it.uppercase() }
return result
}
fun main() {
println(normalizeName(" kotlin ")) // Kotlin
}
Here name is the input data, and result is the working area.
3. Mini app “Step Tracker”
Now we’ll build a small but cohesive example that helps you assemble everything you’ve learned. Let it be a console “weekly step tracker”: the program asks for steps for each day, stores them in an array, and prints the total.
Before, you would have written everything in main, but now we’ll start moving repeated steps into functions. We deliberately keep the code simple so the focus is on functions, not on tricky techniques.
Helper function for printing a header
When a program grows, it’s nice to have a consistent output style.
fun printSection(title: String) {
println()
println("=== $title ===")
}
fun main() {
printSection("Step Tracker")
}
Function that reads a number
We’ll handle input validation later, but even now we can extract “prompt and read” into a separate function.
fun readInt(prompt: String): Int {
print(prompt)
val raw = readln().trim()
val number = raw.toIntOrNull()
if (number == null) return 0
return number
}
fun main() {
val x = readInt("Enter a number: ")
println("You entered: $x") // for example: You entered: 12
}
We’ll cover how return works a bit later; for now, treat it as “the function must produce an Int, so in the end it returns a number”.
Function for reading steps for a day
Now we wrap “input steps for a specific day” into a function with the parameter dayName.
fun readStepsForDay(dayName: String): Int {
return readInt("Steps for $dayName: ")
}
fun main() {
val mondaySteps = readStepsForDay("Monday")
println("Monday: $mondaySteps") // for example: Monday: 5400
}
Notice how the code starts to read naturally: readStepsForDay("Monday") is almost a sentence.
Function to compute the sum over an array
We have an array IntArray. We already know how to iterate over it with a loop and accumulate a sum. Now let’s give that action a name.
fun sumSteps(steps: IntArray): Int {
var total = 0
for (x in steps) {
total += x
}
return total
}
fun main() {
val data = intArrayOf(3000, 5000, 4500)
println(sumSteps(data)) // 12500
}
This function is useful not only in a step tracker: it’s also an example of how a function packages a long loop and returns the final result.
Putting everything into one script in main
Let’s assemble a minimal working “weekly tracker” out of small functions. This piece will be longer than usual—this is fine, because by design main should be a script that a human can read.
fun printSection(title: String) {
println()
println("=== $title ===")
}
fun readInt(prompt: String): Int {
print(prompt)
val raw = readln().trim()
val number = raw.toIntOrNull()
if (number == null) return 0
return number
}
fun readStepsForDay(dayName: String): Int {
return readInt("Steps for $dayName: ")
}
fun sumSteps(steps: IntArray): Int {
var total = 0
for (x in steps) total += x
return total
}
fun main() {
printSection("Weekly Step Tracker")
val days = arrayOf("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
val steps = IntArray(7)
for (i in days.indices) {
steps[i] = readStepsForDay(days[i])
}
val total = sumSteps(steps)
println("Total steps: $total") // for example: Total steps: 42000
}
What’s important and interesting here:
- Each function has a clear name and a small size.
- Parameters show “what’s needed for the work”: dayName, prompt, steps.
- The return type shows “what the function returns”: Int.
- main stopped being a dump of details and turned into a script: “show header → collect data → compute → print”.
4. Common mistakes when declaring and calling functions
Mistake #1: forgot to specify the parameter type.
Beginners are often tempted to write fun greet(name) { ... }, like in some languages. Kotlin can’t do that: the parameter type is required. Correct is fun greet(name: String) { ... }. It’s annoying at first, and then it saves you from very strange bugs where you “passed the wrong thing to the wrong place”.
Mistake #2: mixing up parameters and arguments (and therefore getting confused when explaining).
It may sound like terminology for the sake of terminology, but in practice it helps. Parameters are what’s declared in the function; arguments are what you actually passed in the call. If you call everything “parameters”, at some point you won’t be able to explain to yourself what exactly didn’t match.
Mistake #3: trying to change a parameter inside a function.
After experience with var, you want to “tweak the input value” right in the parameter. Kotlin doesn’t allow reassigning parameters: they behave like val. If you need to modify something, create a local var and modify that. The code becomes a bit longer, but many times clearer.
Mistake #4: a function does too many things at once.
When you’re just starting out, it feels convenient to write fun doAll()—“input, calculation, and printing”. But then the function can’t be reused: you wanted “only calculate”, but it also prints; you wanted “only ask”, but it already pokes into an array. A good rule at the start: one function—one clear step of the script or one computation.
Mistake #5: names like f1, calc, doIt, because “it’s obvious anyway”.
While your program is 20 lines—yes, it’s “obvious”. When it becomes 200—it won’t be. A function name should answer the question “what does it do?” or “what does it return?”. sumSteps reads without comments, while calc2 reads like a quest riddle.
GO TO FULL VERSION