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

Function Composition

In this page:

  1. Function Composition

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
}
🔒

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.