Junior — Middle
How to distinguish functions that accept other functions as arguments from regular functions?
sobes.tech AI
Answer from AI
Functions that accept other functions as arguments are often called higher-order functions. They can be distinguished by their signature: such functions have parameters that are of types representing functions or closures.
For example, in Kotlin (Android):
// Regular function
fun sum(a: Int, b: Int): Int {
return a + b
}
// Higher-order function that takes a function as an argument
fun operateOnNumbers(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}
// Call
val result = operateOnNumbers(3, 4, ::sum) // Passing the sum function as an argument
Here, operation: (Int, Int) -> Int is a function parameter that takes two Ints and returns an Int. Regular functions do not have such parameters.
Thus, to distinguish, you need to look at the parameter types: if among them there are functions or closures, then it is a higher-order function.