Function Composition
In this page:
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
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
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: