← Back to Kotlin Course | Chapter 9: Lambdas & Higher-Order Functions | Lesson 2 of 6

Function Types

A function type describes the shape of a function -- what it takes in and what it gives back -- so you can store a function in a variable like any other value.
Syntax
kotlin
val name: (ParamType) -> ReturnType = { p -> expression }

fun functionName(action: (ParamType) -> ReturnType) {
    action(value)
}

fun other(task: () -> Unit) { task() }

Declaring a Function Type

A function type describes a function's shape: parameter types in parentheses, an arrow, then the return type -- for example (Int, Int) -> Int for a function taking two Ints and returning one.

Example: Declaring a Function Type

markup
// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `multiply` (a `(Int, Int) -> Int`), set to `{ a, b -> a * b }`
    val multiply: (Int, Int) -> Int = { a, b -> a * b }
    // Print "Product: ${multiply(6, 7)}" to the console, with a trailing newline
    println("Product: ${multiply(6, 7)}")
}

Function Types as Parameters

A function can accept another function as a parameter by declaring that parameter with a function type, enabling behavior to be passed in just like any other value.

Example: Function Types as Parameters

markup
// Define the function `applyOperation` taking `a`, `b`, `operation` and returning an Int
fun applyOperation(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
    // Return `operation(a, b)` from this function
    return operation(a, b)
}

// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `result`, set to `applyOperation(4, 5) { x, y -> x + y }`
    val result = applyOperation(4, 5) { x, y -> x + y }
    // Print "Result: $result" to the console, with a trailing newline
    println("Result: $result")
}

Function Types That Return Unit

() -> Unit describes a function with no parameters that performs an action but produces no meaningful value, similar to a void method in other languages.

Example: Function Types That Return Unit

markup
// Define the function `runTask` taking `task`
fun runTask(task: () -> Unit) {
    // Print "Starting task..." to the console, with a trailing newline
    println("Starting task...")
    task()
    // Print "Task finished" to the console, with a trailing newline
    println("Task finished")
}

// Entry point: execution of the program starts here
fun main() {
    runTask { println("Doing work") }
}

Storing Functions in Variables

Because functions are values in Kotlin, a variable can hold a reference to one using a function type, and that variable can later be called just like a regular function.

Example: Storing Functions in Variables

markup
// Entry point: execution of the program starts here
fun main() {
    val operations = mapOf<String, (Int, Int) -> Int>(
        "add" to { a, b -> a + b },
        "subtract" to { a, b -> a - b }
    )
    // Print "5 + 3 = ${operations["add"]!!(5, 3)}" to the console, with a trailing newline
    println("5 + 3 = ${operations["add"]!!(5, 3)}")
    // Print "5 - 3 = ${operations["subtract"]!!(5, 3)}" to the console, with a trailing newline
    println("5 - 3 = ${operations["subtract"]!!(5, 3)}")
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting the parentheses around the parameter types in a function type, writing Int -> Int instead of (Int) -> Int.
  2. Confusing a nullable function type (() -> Unit)? with a function returning a nullable type () -> Unit?; the parentheses placement matters.
  3. Trying to pass a plain value where a function type is expected, instead of a lambda or function reference.
Chapter Summary
  • A function type is written as (ParamTypes) -> ReturnType, such as (Int, Int) -> Int.
  • Variables, parameters, and properties can all be declared with a function type and hold a lambda or function reference.
  • () -> Unit describes a function that takes no parameters and returns nothing meaningful.
  • Function types make it possible to pass behavior itself as data, which is central to higher-order functions.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.