Basic Functions in Kotlin

1. Why Use Functions?

Functions are fundamental building blocks of Kotlin programs. They allow you to group reusable code into logical units, improving readability, reducing redundancy, and making debugging easier.

Instead of repeating the same logic in multiple places, you can define a function once and call it whenever needed — making your code cleaner and more modular.


2. How to Define and Use Functions

A function in Kotlin is declared using the fun keyword, followed by its name, parameters (if any), and return type.


// Basic function example
fun greet() {
    println("Hello, Kotlin!")
}

fun main() {
    greet()  // Output: Hello, Kotlin!
}
    
Function with Parameters

fun greetUser(name: String) {
    println("Welcome, $name!")
}

fun main() {
    greetUser("Talha")  // Output: Welcome, Talha!
}
    
Function with Return Type

fun add(a: Int, b: Int): Int {
    return a + b
}

fun main() {
    val sum = add(10, 5)
    println("Sum is $sum")  // Output: Sum is 15
}
    
Single-Expression Functions

If your function returns a single expression, you can simplify it using expression body syntax:


fun multiply(a: Int, b: Int) = a * b

fun main() {
    println(multiply(4, 6))  // Output: 24
}
    

3. Function Types


// Example of a local function
fun outerFunction() {
    fun innerHelper(x: Int): Int = x * x
    println(innerHelper(5))  // Output: 25
}
    

4. Default and Named Parameters

Kotlin allows you to assign default values to parameters and call functions using named arguments:


fun displayInfo(name: String, age: Int = 18) {
    println("Name: $name, Age: $age")
}

fun main() {
    displayInfo("Ali")               // Uses default age
    displayInfo(name = "Sara", age = 25) // Uses named arguments
}
    

5. When to Use and When Not to Use Functions

Use functions when:
Avoid or simplify functions when:

6. Interview Questions


7. Example Program


fun calculateGrade(score: Int): String {
    return when {
        score >= 90 -> "A"
        score >= 80 -> "B"
        score >= 70 -> "C"
        else -> "Fail"
    }
}

fun main() {
    println("Student Grade: ${calculateGrade(85)}") // Output: Student Grade: B
}
    

Functions in Kotlin not only make your code cleaner but also align with modern programming principles — encouraging readability, reuse, and functional-style design.