Free preview.You're sampling one lesson — enroll free to unlock all 10 lessons and track your progress.
Enroll free lesson
Closures and Higher-Order Functions
Closures and Higher-Order Functions
In this lesson — part of Advanced Features — you'll learn closures and higher-order functions in Scala and why it matters in real work.
Why it matters
Functions that take or return functions unlock concise, composable code.
Key ideas
- Functions as values
- map / filter / reduce
- Callbacks
- Composition
In practice
Here's how it looks in idiomatic Scala:
// takes a function, returns a function
def twice[A](f: A => A): A => A = x => f(f(x))
val addTwo = twice((x: Int) => x + 1)
addTwo(10) // 12
// methods accepting function args; `_` is a placeholder lambda
List(1, 2, 3).map(_ + 1).filter(_ > 2)
// by-name parameter: argument evaluated lazily on each use
def retry[A](n: Int)(body: => A): A =
if n <= 1 then body
else try body catch { case _: Throwable => retry(n - 1)(body) }
Scala note: Beyond ordinary function parameters, Scala has by-name parameters (=> A) that defer evaluation, enabling custom control structures like retry/using that look like built-in syntax.
Try it yourself
Exercise: In Scala, use map and filter to get the squares of the even numbers.
Recap
You now understand closures and higher-order functions and can apply it in Scala. Mark this lesson complete and continue to the next one.
