Functions in Kotlin are treated like any other value. This means you can store them in variables, pass them to other functions, and return them from functions. It makes your code more flexible and reusable.
0
0
Why functions are first-class in Kotlin
Introduction
When you want to pass a small piece of behavior to another function, like sorting or filtering a list.
When you want to store a function in a variable to use it later.
When you want to create functions that return other functions for customization.
When you want to write cleaner and shorter code by using lambdas or anonymous functions.
When you want to build higher-level functions that work with other functions.
Syntax
Kotlin
val myFunction: (Int, Int) -> Int = { a, b -> a + b } fun operate(x: Int, y: Int, op: (Int, Int) -> Int): Int { return op(x, y) }
Functions can be stored in variables using function types like (Int, Int) -> Int.
You can pass functions as parameters to other functions to customize behavior.
Examples
This stores a function that takes a name and returns a greeting.
Kotlin
val greet: (String) -> String = { name -> "Hello, $name!" }
This shows passing a function as an argument to another function.
Kotlin
fun applyOperation(x: Int, y: Int, operation: (Int, Int) -> Int): Int { return operation(x, y) } val sum = applyOperation(3, 4) { a, b -> a + b }
This shows returning a function from a function.
Kotlin
fun makeMultiplier(factor: Int): (Int) -> Int { return { number -> number * factor } } val double = makeMultiplier(2) println(double(5)) // prints 10
Sample Program
This program shows how functions can be stored in variables and passed to another function to perform different operations.
Kotlin
fun main() { val add: (Int, Int) -> Int = { a, b -> a + b } val multiply: (Int, Int) -> Int = { a, b -> a * b } fun calculate(x: Int, y: Int, operation: (Int, Int) -> Int): Int { return operation(x, y) } println(calculate(5, 3, add)) // prints 8 println(calculate(5, 3, multiply)) // prints 15 }
OutputSuccess
Important Notes
Because functions are first-class, Kotlin supports lambdas and anonymous functions easily.
This feature helps write concise and expressive code.
Summary
Functions in Kotlin can be treated like any other value.
You can store, pass, and return functions to make your code flexible.
This helps write reusable and clean code using lambdas and higher-order functions.