Kotlin Functions
A function is a named block of code that performs a specific task. Instead of writing the same logic in multiple places, you define a function once and call it wherever you need it. Functions make code reusable, organized, and easier to test.
Defining a Function
fun greet() {
println("Hello from a function!")
}
fun main() {
greet() // call the function
greet() // call it again — runs the same block
}Anatomy of a Function
fun add (a: Int, b: Int) : Int {
│ │ │ │ │
│ │ └─────────────┘ └── Return type
│ │ Parameters (what it gives back)
│ │
│ └── Function name
└── keyword "fun"
return a + b
│
└── Returns the result to the caller
}
Functions with Parameters
fun greetUser(name: String) {
println("Hello, $name!")
}
fun main() {
greetUser("Alice")
greetUser("Bob")
}Output:
Hello, Alice!
Hello, Bob!Functions with Return Values
fun add(a: Int, b: Int): Int {
return a + b
}
fun multiply(x: Double, y: Double): Double {
return x * y
}
fun main() {
val sum = add(10, 25)
println("Sum: $sum") // Sum: 35
val product = multiply(3.5, 2.0)
println("Product: $product") // Product: 7.0
}Single Expression Functions
When a function's body is one expression, use the shorthand = syntax:
fun square(n: Int): Int = n * n
fun isEven(n: Int): Boolean = n % 2 == 0
fun fullName(first: String, last: String): String = "$first $last"
fun main() {
println(square(7)) // 49
println(isEven(14)) // true
println(fullName("Ada", "Lovelace")) // Ada Lovelace
}Unit Return Type
Functions that do not return a value have the return type Unit. You can write it explicitly or leave it out — both are the same:
fun printMessage(msg: String): Unit {
println(msg)
}
// Same as:
fun printMessage(msg: String) {
println(msg)
}Multiple Parameters
fun calculateBill(price: Double, quantity: Int, taxRate: Double): Double {
val subtotal = price * quantity
val tax = subtotal * taxRate
return subtotal + tax
}
fun main() {
val total = calculateBill(250.0, 4, 0.12)
println("Total bill: $total") // Total bill: 1120.0
}Function Flow Diagram
main() calls add(10, 25)
│
▼
fun add(a=10, b=25)
a + b = 35
return 35
│
▼
val sum = 35
println("Sum: 35")
Practical Example: Grade Calculator
fun getGrade(score: Int): String {
return when {
score >= 90 -> "A"
score >= 75 -> "B"
score >= 60 -> "C"
score >= 50 -> "D"
else -> "F"
}
}
fun printResult(name: String, score: Int) {
val grade = getGrade(score)
println("Student: $name | Score: $score | Grade: $grade")
}
fun main() {
printResult("Priya", 88)
printResult("Rajan", 63)
printResult("Neha", 45)
}Output:
Student: Priya | Score: 88 | Grade: B
Student: Rajan | Score: 63 | Grade: C
Student: Neha | Score: 45 | Grade: F