0PricingLogin
Scala for Backend Engineering & Functional Programming · Lesson

Composition

andThen and compose.

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

All lessons in this course

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