WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Scala · Basic · question 8 of 100

What are higher-order functions in Scala? Provide an example.?

📕 Buy this interview preparation book: 100 Scala questions & answers — PDF + EPUB for $5

Higher-order functions are functions that can take other functions as arguments, or return a function as a result or both. In Scala, functions are first-class values, which means they can be passed as arguments to other functions, assigned to variables, and returned from other functions. Higher-order functions allow you to create more abstract and flexible code that is easier to reuse and compose.

Here’s an example of a higher-order function ‘applyOperation‘ which takes two integers ‘a‘ and ‘b‘, and a function ‘operation‘ that takes two integers and returns another integer. ‘applyOperation‘ calls the ‘operation‘ function with ‘a‘ and ‘b‘ as arguments, and then returns the result:

def applyOperation(a: Int, b: Int, operation: (Int, Int) => Int): Int = {
  operation(a, b)
}

In this example, ‘(Int, Int) => Int‘ is the type signature of the function that ‘applyOperation‘ accepts as its third parameter. It specifies a function that takes two ‘Int‘ parameters and returns an ‘Int‘.

You can use the ‘applyOperation‘ function to apply different mathematical operations to the provided integers:

// Function to add two numbers
val add = (x: Int, y: Int) => x + y

// Function to multiply two numbers
val multiply = (x: Int, y: Int) => x * y

// Using the applyOperation function

val sum = applyOperation(3, 4, add)
println(s"3 + 4 = $sum") // Output: 3 + 4 = 7

val product = applyOperation(3, 4, multiply)
println(s"3 * 4 = $product") // Output: 3 * 4 = 12

Another common example of higher-order functions in Scala is the use of ‘map‘, ‘filter‘, and ‘reduce‘ on collections. These functions take other functions as arguments to perform transformations, filtering, or aggregation on the elements of the collection. For instance:

val numbers = List(1, 2, 3, 4, 5)

// Square each number in the list
val squares = numbers.map(x => x * x)
println(squares) // Output: List(1, 4, 9, 16, 25)

// Filter out even numbers from the list
val evens = numbers.filter(x => x % 2 == 0)
println(evens) // Output: List(2, 4)

// Calculate the sum of all numbers in the list using reduce
val sum = numbers.reduce((acc, x) => acc + x)
println(sum) // Output: 15

Higher-order functions are an important concept in functional programming and can help make your Scala code more modular, reusable, and expressive.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Scala interview — then scores it.
📞 Practice Scala — free 15 min
📕 Buy this interview preparation book: 100 Scala questions & answers — PDF + EPUB for $5

All 100 Scala questions · All topics