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:
Syntax
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 gapplies f then g (left to right).f compose gapplies 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
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
- Mixing up
andThenandcompose, whenf andThen grunsffirst andf compose grunsgfirst. - Composing functions whose types do not match, such as a
Stringresult feeding anIntfunction. - 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: