How to Use Function Type in Kotlin: Syntax and Examples
In Kotlin, a
function type describes a type of function by specifying its parameter types and return type, like (Int, Int) -> Int. You can use function types to declare variables, parameters, or return types that hold or return functions.Syntax
A function type in Kotlin is written as (ParameterType1, ParameterType2, ...) -> ReturnType. For example, (Int, Int) -> Int means a function that takes two integers and returns an integer. You can declare variables or parameters with this type to hold functions matching that signature.
kotlin
val sum: (Int, Int) -> Int = { a, b -> a + b }
fun operate(x: Int, y: Int, op: (Int, Int) -> Int): Int {
return op(x, y)
}Example
This example shows how to declare a function type variable, pass it as a parameter, and call it.
kotlin
fun main() {
val multiply: (Int, Int) -> Int = { a, b -> a * b }
fun calculate(x: Int, y: Int, operation: (Int, Int) -> Int): Int {
return operation(x, y)
}
val result = calculate(4, 5, multiply)
println("Result: $result")
}Output
Result: 20
Common Pitfalls
One common mistake is mismatching the function type signature, such as wrong parameter count or types. Another is forgetting to use parentheses when calling a function stored in a variable. Also, using Unit as return type means the function returns nothing, so returning a value causes errors.
kotlin
fun main() {
// Wrong: parameter types do not match
// val wrongFunc: (Int, String) -> Int = { a, b -> a + b.length } // Error if used incorrectly
// Correct usage
val correctFunc: (Int, String) -> Int = { a, b -> a + b.length }
// Calling function variable
println(correctFunc(3, "Hi")) // Prints 5
// Forgetting parentheses when calling
val f: () -> Unit = { println("Hello") }
// f // This just references the function, does not call it
f() // Correct call
}Output
5
Hello
Quick Reference
| Concept | Example | Description |
|---|---|---|
| Function type syntax | (Int, Int) -> Int | Function taking two Ints and returning Int |
| Variable declaration | val f: (String) -> Unit | Variable holding a function taking String and returning nothing |
| Passing function | fun run(op: () -> Unit) | Function parameter expecting a function with no params and no return |
| Calling function variable | f() | Invoke the function stored in variable f |
| Lambda expression | { x -> x * 2 } | Anonymous function matching a function type |
Key Takeaways
Function types describe the input and output types of functions in Kotlin.
You can store functions in variables, pass them as parameters, and return them using function types.
Always match the function type signature exactly to avoid errors.
Use parentheses to call functions stored in variables.
Function types with Unit return type mean the function returns no value.