Skip to Content
Course content

17: Higher-Order Functions

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Wait, what actually makes a function "higher-order"?

It sounds like academic jargon, but it's actually a very simple concept. In Scala, functions are "first-class citizens," meaning you can treat a function just like you'd treat an Integer or a String. A Higher-Order Function (HOF) is simply a function that does at least one of two things: it takes another function as an argument, or it returns a function as its result.

I like to think of HOFs as "logic templates." Instead of writing five different functions to handle five different types of data processing, you write one HOF that defines the process and let the caller pass in the specific logic. Look at this example—instead of writing separate methods for different types of price adjustments, we can just pass the logic in:

def applyAdjustment(price: Double, strategy: Double => Double): Double = {
  strategy(price)
}

val holidayDiscount = applyAdjustment(100.0, p => p * 0.8) 
val taxAddition = applyAdjustment(100.0, p => p * 1.15)

println(s"Holiday: $holidayDiscount, Taxed: $taxAddition")

How do I actually write the type for a function parameter?

This is usually where people get tripped up. You aren't passing a class or an object; you're passing a function signature. In Scala, we use the => syntax to describe this. If you see Int => Boolean, it means "a function that takes an Int and returns a Boolean."

If you're building something like a custom validator for a user registration form, you wouldn't want to hardcode every single rule into one giant method. Instead, you can define a validator HOF. I've used this pattern a thousand times to keep my business logic clean:

def validateInput(input: String, check: String => Boolean): String = {
  if (check(input)) "Valid!" else "Invalid input provided."
}

val isTooShort = validateInput("Hi", s => s.length > 5)
val hasNoNumbers = validateInput("Scala123", s => !s.exists(_.isDigit))

println(isTooShort) // Invalid input provided.
println(hasNoNumbers) // Invalid input provided.

Can a function really return another function?

Yes, and this is where things get powerful. This is often used for "configuration" or creating specialized versions of a function. Instead of passing all your arguments at once, you can create a function that generates the function you actually need.

Think of it like a factory. Let's say you're building a logging system where you want different levels of urgency. You can write a function that returns a tailored logger:

def createLogger(level: String): String => Unit = {
  // This returns an anonymous function that takes a message
  message => println(s"[$level] $message")
}

val infoLog = createLogger("INFO")
val errorLog = createLogger("ERROR")

infoLog("System started successfully.") 
errorLog("NullPointerException at line 42!")

I'll be honest: when I first saw this, it felt like over-engineering. But once you start dealing with complex dependency injection or middleware, you'll realize that returning functions is the cleanest way to "preset" certain behaviors without carrying around a bunch of state in an object.

When should I use an HOF instead of just a regular method?

The rule of thumb I use is: if you find yourself writing three methods that are identical except for one small piece of logic in the middle, you need a Higher-Order Function. You're basically separating the orchestration (the loop, the error handling, the logging) from the execution (the specific calculation).

You've probably already used HOFs without realizing it. Every time you use .map(), .filter(), or .fold() on a collection, you are using a higher-order function. .filter() doesn't know what it's filtering for; it just knows how to iterate through a list and keep the items that satisfy the function you passed into it. That decoupling is exactly what makes Scala so expressive.




📋 Practical Task

Exercise: The Flexible Order Discount Engine

You are building a checkout system for an e-commerce site. Instead of creating a dozen different methods for different promotion types (Seasonal, VIP, First-Time Buyer), you need to implement a higher-order function that applies a discount strategy to a total order amount.

Your Task:

  • Create a function called calculateTotal that takes two parameters:
    1. amount: Double (the original price)
    2. discountStrategy: Double => Double (a function that defines how to modify the price)
  • Implement three different discount strategies as anonymous functions:
    • A 20% flat discount.
    • A fixed $10 off (but the price cannot go below 0).
    • A "Buy 1 Get 1" style 50% discount.
  • Call calculateTotal using each of these strategies with an initial amount of 100.0 and print the results.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.