Kotlin Functions
A function is a named block of code that performs a specific task. Instead of writing the same code multiple times, you write it once in a function and call it by name whenever you need it. Functions are the building blocks of every Kotlin program.
Defining and Calling a Function
fun greet() {
println("Hello, welcome to eStudy247!")
}
fun main() {
greet() // Calling the function
greet() // Call it again — same code, no repetition
}
Anatomy of a Function
fun greet () {
↑ ↑ ↑ ↑
| | | └── Function body (code that runs)
| | └── Parameter list (empty here)
| └── Function name
└── Keyword to declare a function
Functions with Parameters
Parameters let you pass information into a function. Each parameter has a name and a type.
fun greet(name: String) {
println("Hello, $name!")
}
fun main() {
greet("Priya") // Hello, Priya!
greet("Arjun") // Hello, Arjun!
}
Multiple Parameters
fun introduce(name: String, age: Int) {
println("I am $name and I am $age years old.")
}
introduce("Kiran", 24)
// Output: I am Kiran and I am 24 years old.
Functions with Return Values
A function can calculate something and send the result back using the return keyword. Specify the return type after the parameter list with a colon.
fun add(a: Int, b: Int): Int {
return a + b
}
val result = add(10, 5)
println(result) // 15
Diagram — Function Flow with Return
Caller Function
------ --------
add(10, 5) ──────► a=10, b=5
│
▼
return 15
result = 15 ◄──────
Single-Expression Functions
When a function body is just one expression, you can write it in a single line using the = sign. Kotlin infers the return type automatically.
fun square(n: Int) = n * n fun isEven(n: Int) = n % 2 == 0 println(square(6)) // 36 println(isEven(7)) // false
Default Parameter Values
You can give a parameter a default value. The caller can skip that argument and the default applies automatically.
fun showMessage(msg: String, times: Int = 1) {
repeat(times) { println(msg) }
}
showMessage("Hello") // prints Hello once
showMessage("Kotlin!", 3) // prints Kotlin! three times
Named Arguments
Named arguments let you pass values in any order by specifying the parameter name. This makes long function calls easier to read.
fun createProfile(name: String, city: String, age: Int) {
println("$name | $city | $age")
}
// Without named arguments — order matters
createProfile("Meera", "Delhi", 26)
// With named arguments — order does not matter
createProfile(city = "Mumbai", age = 30, name = "Raj")
vararg — Variable Number of Arguments
The vararg keyword lets a function accept any number of arguments of the same type.
fun sumAll(vararg numbers: Int): Int {
var total = 0
for (n in numbers) total += n
return total
}
println(sumAll(1, 2, 3)) // 6
println(sumAll(10, 20, 30, 40)) // 100
Unit Return Type
When a function does not return a value, its return type is Unit. This is equivalent to void in Java. You can write it explicitly or leave it out — both are correct.
fun logMessage(msg: String): Unit {
println("[LOG] $msg")
}
// Same thing, Unit is optional:
fun logMessage(msg: String) {
println("[LOG] $msg")
}
Local Functions
You can define a function inside another function. The inner function is only visible within the outer function. This keeps helper logic private and close to where it is used.
fun processOrder(orderId: Int) {
fun validate(id: Int): Boolean {
return id > 0
}
if (validate(orderId)) {
println("Order $orderId is valid.")
} else {
println("Invalid order ID.")
}
}
processOrder(101) // Order 101 is valid.
Recursion — A Function Calling Itself
A recursive function calls itself to solve smaller versions of the same problem. Every recursive function needs a base case — a condition that stops the recursion.
fun factorial(n: Int): Int {
if (n == 0) return 1 // Base case — stop here
return n * factorial(n - 1) // Recursive call
}
println(factorial(5)) // 120
// How it works:
// factorial(5) = 5 * factorial(4)
// = 5 * 4 * factorial(3)
// = 5 * 4 * 3 * factorial(2)
// = 5 * 4 * 3 * 2 * factorial(1)
// = 5 * 4 * 3 * 2 * 1 * factorial(0)
// = 5 * 4 * 3 * 2 * 1 * 1 = 120
