Function types in Kotlin are a powerful feature that allows you to treat functions as first-class citizens. They enable you to pass functions as arguments, return them from other functions, and store them in variables.
A function type in Kotlin is represented by a set of parameter types enclosed in parentheses, followed by an arrow (->) and the return type. For example:
(Int, Int) -> Int
This function type represents a function that takes two Integer parameters and returns an Integer.
You can declare variables or parameters of function types:
val sum: (Int, Int) -> Int = { a, b -> a + b }
fun applyOperation(x: Int, y: Int, operation: (Int, Int) -> Int): Int {
return operation(x, y)
}
Function types are often used in conjunction with Kotlin Lambda Expressions:
val numbers = listOf(1, 2, 3, 4, 5)
val squared = numbers.map { it * it }
println(squared) // Output: [1, 4, 9, 16, 25]
Function types can be nullable by adding a question mark after the type:
var nullableFunc: ((Int) -> Int)? = null
nullableFunc = { it * 2 }
println(nullableFunc?.invoke(5)) // Output: 10
Kotlin also supports function types with receivers, which are similar to extension functions:
val isEven: Int.() -> Boolean = { this % 2 == 0 }
println(4.isEven()) // Output: true
Function types in Kotlin are a cornerstone of functional programming. They provide a way to work with functions as values, enabling more expressive and concise code. By mastering function types, you'll be able to write more flexible and powerful Kotlin applications.