Scala
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Scala
-
Section 4: Functional Scala
-
Section 5: Collections in Depth
-
Section 6: Type System
-
Section 7: Concurrency and Ecosystem
-
Section 8: Practical Projects
-
Section 9: Interview Practice
-
Section 10: Data Structures and Algorithms in Scala
-
Section 11: More Practice Exercises
-
Section 12: Advanced Functional Patterns
-
Section 13: More Ecosystem
-
Section 14: Scala Collections Library Deep Dive
-
Section 15: Scala Standard Library Deep Dive
-
Section 16: Akka Ecosystem Deep Dive
-
Section 17: Cats and Cats Effect Deep Dive
-
Section 18: Play Framework Deep Dive
-
Section 19: Apache Spark with Scala Deep Dive
-
Section 20: Scala Build Tools Deep Dive
-
Section 21: Scala 3 Specific Features
-
90: Union and Intersection Types
-
Section 22: Scala Testing Deep Dive
-
Section 23: Functional Domain Modeling
-
Section 24: More Data Structures and Algorithms in Scala
-
Section 25: Scala for Data Engineering
-
Section 26: More Practical Projects
-
Section 27: More Interview and Review
-
Section 28: ZIO Ecosystem Deep Dive
-
Section 29: Scala for Machine Learning
-
Section 30: Scala Microservices Architecture
-
Section 31: Scala Type System Deep Dive
-
Section 32: More Practice and Drills
-
Section 33: Scala Performance Deep Dive
-
Section 34: Scala Ecosystem Tooling
-
Section 35: Scala for Reactive Systems
-
Section 36: More Real-World Case Studies
-
Section 37: Scala for Financial Systems
-
Section 38: Scala GraphQL and gRPC
-
Section 39: More Final Projects
-
Section 40: More Interview and Final Review
-
Section 41: Scala for Streaming Data
-
Section 42: Scala Security Practices
-
Section 43: More Language Deep Dive
-
Section 44: Scala Command-Line Tools
-
Section 45: Scala Documentation and Style
-
Section 46: Scala Dependency Management
-
Section 47: More Practical Backend Patterns
-
Section 48: Scala for Event-Driven Architecture
-
Section 49: More Practice Drills Round 2
-
Section 50: Scala Compiler Deep Dive
-
Section 51: Scala for Web Frontends
-
Section 52: More Data Engineering Practice
-
Section 53: Scala Observability
-
Section 54: More Advanced Practice Projects
-
Section 55: Scala for Legacy Java Integration
-
Section 56: More Testing Practice
-
Section 57: Final Mastery Review
-
Section 58: Scala History and Ecosystem Context
-
Section 59: More Concurrency Patterns
-
Section 60: Scala for Configuration Management
-
Section 61: More Domain Modeling Practice
17: Higher-Order Functions
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
calculateTotalthat takes two parameters:amount: Double(the original price)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
calculateTotalusing each of these strategies with an initial amount of100.0and print the results.
There are no comments for now.