← Back to Scala Course | Chapter 9: Functional Programming | Lesson 7 of 8

Function Composition

Function composition chains two functions so that the output of one goes into the next, like an assembly line. andThen and compose join them in either order.

In this page:

  1. Function Composition
Syntax
scala
val combined1 = f andThen g    // g(f(x))
val combined2 = f compose g    // f(g(x))

Function Composition

andThen and compose combine two functions into a new one: f andThen g runs f first then feeds its result into g, while f compose g runs g first then feeds its result into f -- the opposite order.

This lets you build complex transformations out of small, reusable, single-purpose functions. Composition is a hallmark of functional programming style, favoring small pieces glued together over one large function.

Note:
  • f andThen g applies f then g (left to right).
  • f compose g applies g then f (right to left) -- easy to mix up.

Example: Function Composition

markup
object Main extends App {
  val addOne: Int => Int = _ + 1
  val double: Int => Int = _ * 2

  val addThenDouble = addOne andThen double
  val doubleThenAdd = addOne compose double

  println(addThenDouble(3)) // (3+1)*2 = 8
  println(doubleThenAdd(3)) // (3*2)+1 = 7
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Mixing up andThen and compose, when f andThen g runs f first and f compose g runs g first.
  2. Composing functions whose types do not match, such as a String result feeding an Int function.
  3. Forgetting that the result is a new function and must still be called with an argument.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.