CodeToLive

Kotlin Functions & Lambdas

Learn how to define and use functions and lambdas in Kotlin.

Basic Function

// Function with parameters and return type
fun add(a: Int, b: Int): Int {
    return a + b
}

// Single-expression function
fun multiply(a: Int, b: Int): Int = a * b

// Function call
val sum = add(3, 4)  // 7

Default Arguments

// Function with default parameters
fun greet(name: String = "Guest") {
    println("Hello, $name!")
}

greet()         // Hello, Guest!
greet("Alice")  // Hello, Alice!

Named Arguments

fun createUser(
    name: String,
    age: Int,
    isAdmin: Boolean = false
) { /* ... */ }

// Using named arguments
createUser(age = 25, name = "Alice")

Extension Functions

// Add function to String class
fun String.addExclamation(): String {
    return "$this!"
}

println("Hello".addExclamation())  // Hello!

Higher-Order Functions

// Function that takes another function as parameter
fun operateOnNumbers(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
    return operation(a, b)
}

// Using with lambda
val result = operateOnNumbers(5, 3) { x, y -> x + y }  // 8

Lambda Expressions

// Lambda assigned to variable
val square: (Int) -> Int = { x -> x * x }
println(square(5))  // 25

// Lambda with implicit parameter
val double = { x: Int -> x * 2 }
println(double(4))  // 8
← Back to Tutorials