compose: Reverse Function Composition
You'll learn how to use compose to apply one function before another, creating a reverse-order transformation pipeline.
What is compose?
While andThen chains functions left-to-right, compose works in the opposite direction. When you call f.compose(g), the result is a new function that first applies g, then applies f to that result. Think of it like reading right-to-left instead of left-to-right.
The Mental Model
Imagine you're preparing a meal. With andThen, you'd say "chop the vegetables, then cook them." With compose, you'd say "cook the result of chopping" — the instruction reads backward, but the execution order (chop first, cook second) stays the same.
Syntax and Usage
Function<Integer, Integer> triple = x -> x * 3;
Function<Integer, Integer> addTwo = x -> x + 2;
// compose: addTwo happens FIRST, triple happens SECOND
Function<Integer, Integer> tripleAfterAddTwo = triple.compose(addTwo);
System.out.println(tripleAfterAddTwo.apply(5)); // (5 + 2) * 3 = 21
Compare this to andThen:
// andThen: triple happens FIRST, addTwo happens SECOND
Function<Integer, Integer> addTwoAfterTriple = triple.andThen(addTwo);
System.out.println(addTwoAfterTriple.apply(5)); // (5 * 3) + 2 = 17
Why Use compose?
Use compose when you're building a transformation from the "inside out" — when you naturally think about the last step first, then work backward to define what needs to happen before it.
Key Takeaway: compose creates reverse-order function chains where the argument function executes before the calling function, enabling inside-out pipeline construction.