Kotlin Functions

Kotlin functions can be top-level, members, local, or extension functions.

Basic Function

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

Expression Body

Kotlin
fun double(n: Int) = n * 2

fun greet(name: String) = "Hello, $name!"

Default and Named Arguments

Kotlin
fun createUser(name: String, age: Int = 18, role: String = "student") {
    println("$name, age $age, role $role")
}

createUser("Ram")                        // defaults
createUser("Sita", age = 21, role = "admin")

Extension Functions

Add methods to existing classes without modifying them:

Kotlin
fun String.isEmail(): Boolean {
    return contains("@") && contains(".")
}

println("user@example.com".isEmail())  // true

Higher-Order Functions

Kotlin
val numbers = listOf(1, 2, 3, 4, 5)

val doubled = numbers.map { it * 2 }         // [2, 4, 6, 8, 10]
val evens = numbers.filter { it % 2 == 0 }    // [2, 4]
val sum = numbers.reduce { acc, n -> acc + n } // 15

Coroutines

Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    launch {
        delay(1000)
        println("Coroutine done")
    }
    println("Hello")
}
// Prints "Hello" then "Coroutine done" after 1s