Skip to content

Scala Higher-order functions!

At this moment I do not have a personal relationship with a computer.

Janet Reno

Higher-order functions are functions that take other functions as arguments or return functions as their results. Scala is a functional programming language, and higher-order functions are a fundamental feature of functional programming.

Here’s an example of a higher-order function in Scala:

def operateOnList(list: List[Int], operator: Int => Int): List[Int] = {
  list.map(operator)
}

In this example, operateOnList is a higher-order function that takes a list of integers and a function operator as its arguments. The operator function takes an integer and returns an integer. operateOnList applies the operator function to each element of the input list using the map function and returns a new list of integers.

Here’s how we can use the operateOnList function with a lambda function:

val list = List(1, 2, 3, 4, 5)
val squaredList = operateOnList(list, x => x * x)
println(squaredList) // Output: List(1, 4, 9, 16, 25)

In this example, we pass a lambda function that squares each element of the input list to the operateOnList function. The map function applies the lambda function to each element of the list, resulting in a new list of squared values.

Higher-order functions are an important feature of Scala, as they enable us to write concise and reusable code. They are used extensively in functional programming and are essential for programming in a functional style.

Published inPersonal PostsScalaTechnical Posts