0
0
KotlinHow-ToBeginner · 3 min read

How to Use Function as Parameter in Kotlin: Simple Guide

In Kotlin, you can pass a function as a parameter by specifying its type using the syntax (ParameterTypes) -> ReturnType. This allows you to call the passed function inside another function, enabling flexible and reusable code.
📐

Syntax

To use a function as a parameter in Kotlin, declare the parameter with the function type (InputTypes) -> ReturnType. Inside the function, you can call this parameter like a normal function.

  • ParameterTypes: The types of inputs the function accepts.
  • ReturnType: The type of value the function returns.
kotlin
fun operateOnNumbers(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
    return operation(a, b)
}
💻

Example

This example shows how to pass a function that adds two numbers as a parameter and use it inside another function.

kotlin
fun operateOnNumbers(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
    return operation(a, b)
}

fun add(x: Int, y: Int): Int {
    return x + y
}

fun main() {
    val result = operateOnNumbers(5, 3, ::add)
    println("Result: $result")
}
Output
Result: 8
⚠️

Common Pitfalls

Common mistakes include:

  • Not matching the function type signature exactly when passing the function.
  • Forgetting to use the :: operator when passing a named function reference.
  • Trying to pass a function with incompatible parameter or return types.

Always ensure the function parameter types and return type match the expected signature.

kotlin
fun operateOnNumbers(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
    return operation(a, b)
}

// Wrong: Passing a function with wrong signature
// fun wrongAdd(x: Int): Int = x + 1
// val result = operateOnNumbers(5, 3, ::wrongAdd) // Error

// Correct:
fun add(x: Int, y: Int): Int = x + y
val result = operateOnNumbers(5, 3, ::add)
📊

Quick Reference

Tips for using functions as parameters in Kotlin:

  • Use (InputTypes) -> ReturnType to declare function types.
  • Pass named functions with ::functionName.
  • Use lambda expressions for inline functions.
  • Ensure parameter and return types match exactly.

Key Takeaways

Declare function parameters using the syntax (InputTypes) -> ReturnType in Kotlin.
Pass named functions using the :: operator to match the expected function type.
Ensure the function signature matches exactly to avoid type errors.
You can also pass lambda expressions directly as function parameters.
Using functions as parameters makes your code more flexible and reusable.