Kotlin

Lambdas and Function Types

admin by @admin ADMIN
46m ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
Kotlin functions are first-class values. A lambda is `{ args -> body }`; its type is `(InputTypes) -> ReturnType`. Single-argument lambdas can use the implicit `it` parameter.
Kotlin
Raw
fun main() {
    // Lambda assigned to a val
    val square: (Int) -> Int = { n -> n * n }
    println(square(5))                              // 25

    // Implicit `it` for single-arg lambdas
    val nums = listOf(1, 2, 3, 4, 5)
    println(nums.filter { it > 2 })                 // [3, 4, 5]
    println(nums.map { it * it })                   // [1, 4, 9, 16, 25]

    // Trailing-lambda syntax — last arg can move outside the parens
    nums.forEach { println(it) }
    // equivalent to: nums.forEach({ println(it) })

    // Higher-order — function that takes a function
    fun applyTwice(n: Int, f: (Int) -> Int): Int = f(f(n))
    println(applyTwice(3) { it + 10 })              // 23

    // Function references with ::
    fun double(n: Int) = n * 2
    println(nums.map(::double))                     // [2, 4, 6, 8, 10]
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.