Junior — Middle
Explain what higher-order functions are and how they are used in programming.
sobes.tech AI
Answer from AI
Higher-order functions are functions that accept other functions as arguments or return functions as results. They are widely used to increase the flexibility and reusability of code.
For example, in Kotlin for Android, you can use a higher-order function to handle clicks:
fun setOnClickListener(action: () -> Unit) {
// call the passed function on click
action()
}
// Usage:
setOnClickListener {
println("Button clicked")
}
This allows passing behavior as a parameter, simplifying the code and making it more expressive.