🔴 Scala
Beginner
What are higher-order functions in Scala?
Answer
Higher-order functions are functions that take other functions as parameters or return functions as results. In Scala, functions are first-class values. Common higher-order functions on collections: map: transform each element: List(1,2,3).map(_ * 2) // List(2,4,6). filter: keep elements matching a predicate: List(1,2,3,4).filter(_ % 2 == 0) // List(2,4). reduce/fold: combine elements: List(1,2,3).foldLeft(0)(_ + _) // 6. flatMap: map then flatten: List(1,2,3).flatMap(x => List(x, x*2)). Function as parameter: def applyTwice(f: Int => Int, x: Int) = f(f(x)). Returning a function: def multiplier(n: Int): Int => Int = x => x * n; val double = multiplier(2). Higher-order functions enable concise, expressive, and composable code.