0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

Composition

andThen and compose.

Composition is a free Scala for Backend Engineering & Functional Programming lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Scala for Backend Engineering & Functional Programming learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Combining functions

Function composition means building a new function by connecting two existing ones, so the output of one becomes the input of the next. Scala provides andThen and compose for this.

object Main {
  def main(args: Array[String]): Unit = {
    val addOne = (x: Int) => x + 1
    val double = (x: Int) => x * 2
    val both = addOne andThen double
    println(both(5))
  }
}

andThen: left to right

f andThen g runs f first, then g. Reading left to right matches the order of execution, which many find intuitive.

  • (f andThen g)(x) == g(f(x))
object Main {
  def main(args: Array[String]): Unit = {
    val addOne = (x: Int) => x + 1
    val triple = (x: Int) => x * 3
    val pipeline = addOne andThen triple
    println(pipeline(4))  // (4 + 1) * 3
  }
}

compose: right to left

f compose g runs g first, then f, the mathematical order f(g(x)).

  • (f compose g)(x) == f(g(x))
object Main {
  def main(args: Array[String]): Unit = {
    val addOne = (x: Int) => x + 1
    val triple = (x: Int) => x * 3
    val pipeline = addOne compose triple
    println(pipeline(4))  // (4 * 3) + 1
  }
}

andThen vs compose

The two are mirror images:

  • f andThen g = g compose f
  • f compose g = g andThen f

Pick whichever reads more naturally for your situation.

object Main {
  def main(args: Array[String]): Unit = {
    val f = (x: Int) => x + 10
    val g = (x: Int) => x * 2
    println((f andThen g)(3))
    println((g compose f)(3))
  }
}

Chaining several functions

You can chain many functions with repeated andThen to build a longer pipeline that flows top to bottom.

object Main {
  def main(args: Array[String]): Unit = {
    val clean = (s: String) => s.trim
    val lower = (s: String) => s.toLowerCase
    val bang  = (s: String) => s + "!"
    val process = clean andThen lower andThen bang
    println(process("  HELLO  "))
  }
}

Composition changes types

The composed functions need compatible types: the output type of the first must match the input type of the second. The pipeline can change types along the way.

object Main {
  def main(args: Array[String]): Unit = {
    val length = (s: String) => s.length
    val isLong = (n: Int) => n > 5
    val check = length andThen isLong
    println(check("scala"))
    println(check("functional"))
  }
}

The identity function

identity returns its input unchanged. It is the neutral element of composition: f andThen identity == f. Useful as a default in folds and conditionals.

object Main {
  def main(args: Array[String]): Unit = {
    val f = (x: Int) => x * 2
    val same = f andThen identity[Int]
    println(same(7))
  }
}

Composing with reduce

Since functions are values, you can store several in a list and compose them all using reduce with andThen.

object Main {
  def main(args: Array[String]): Unit = {
    val steps: List[Int => Int] = List(_ + 1, _ * 2, _ - 3)
    val pipeline = steps.reduce(_ andThen _)
    println(pipeline(5))  // ((5+1)*2)-3
  }
}

Building reusable pipelines

Composition encourages small, single-purpose functions that you assemble into larger behavior, a key idea in functional programming.

object Main {
  def main(args: Array[String]): Unit = {
    val sanitize = (s: String) => s.trim.toLowerCase
    val capitalize = (s: String) => s.capitalize
    val format = sanitize andThen capitalize
    println(format("  aLiCe "))
  }
}

Composition with map

A composed function is just a function, so you can pass it straight to map to apply the whole pipeline across a collection.

object Main {
  def main(args: Array[String]): Unit = {
    val transform = ((x: Int) => x + 1) andThen ((x: Int) => x * x)
    println(List(1, 2, 3).map(transform))
  }
}

Reading composition order carefully

A common bug is confusing andThen and compose. Always remember: andThen = first this, then that; compose = the reverse.

object Main {
  def main(args: Array[String]): Unit = {
    val inc = (x: Int) => x + 1
    val sqr = (x: Int) => x * x
    println((inc andThen sqr)(2))  // (2+1)^2 = 9
    println((inc compose sqr)(2))  // (2^2)+1 = 5
  }
}

Quick Check

Given f and g, what does (f andThen g)(x) compute?

Recap

You learned function composition:

  • f andThen gg(f(x)) (left to right)
  • f compose gf(g(x)) (right to left)
  • They are mirror images of each other
  • identity is the neutral element
  • Compose lists of functions with reduce(_ andThen _)

Frequently asked questions

Is the “Composition” lesson free?

Yes — the full text of “Composition” is free to read here on the web, and the Scala for Backend Engineering & Functional Programming course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Scala for Backend Engineering & Functional Programming course, upgrade to CoddyKit PRO.

What will I learn in “Composition”?

andThen and compose. You practise Scala for Backend Engineering & Functional Programming with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Scala for Backend Engineering & Functional Programming?

No prior experience is required. Scala for Backend Engineering & Functional Programming on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Composition” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Scala for Backend Engineering & Functional Programming lesson?

Yes. Every Scala for Backend Engineering & Functional Programming lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Functions as Values
  2. Currying
  3. Composition
  4. Closures
← Back to Scala for Backend Engineering & Functional Programming