Function Types
In this page:
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
fun main() {
val multiply: (Int, Int) -> Int = { a, b -> a * b }
println("Product: ${multiply(6, 7)}")
}
Login to try C/C++/Java/PHP code in the editor
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
fun applyOperation(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}
fun main() {
val result = applyOperation(4, 5) { x, y -> x + y }
println("Result: $result")
}
Login to try C/C++/Java/PHP code in the editor
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
fun runTask(task: () -> Unit) {
println("Starting task...")
task()
println("Task finished")
}
fun main() {
runTask { println("Doing work") }
}
Login to try C/C++/Java/PHP code in the editor
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
fun main() {
val operations = mapOf<String, (Int, Int) -> Int>(
"add" to { a, b -> a + b },
"subtract" to { a, b -> a - b }
)
println("5 + 3 = ${operations["add"]!!(5, 3)}")
println("5 - 3 = ${operations["subtract"]!!(5, 3)}")
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting the parentheses around the parameter types in a function type, writing
Int -> Intinstead of(Int) -> Int. - Confusing a nullable function type
(() -> Unit)?with a function returning a nullable type() -> Unit?; the parentheses placement matters. - Trying to pass a plain value where a function type is expected, instead of a lambda or function reference.
- 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.
() -> Unitdescribes 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: