Home

andThen

andThen is a functional programming concept that denotes the sequential application of two functions. If f maps A to B and g maps B to C, then the expression f andThen g represents a new function from A to C defined by applying f to an input and then applying g to the result. This is a form of function composition and is commonly contrasted with compose, which applies the functions in the opposite order (for example, g andThen f is not the same as f compose g unless the functions commute).

Mathematically, if f: A -> B and g: B -> C, then (f andThen g)(x) = g(f(x)). The operation

In programming languages, andThen appears as a method or operator on function types. In Java, the Function

Common uses include building readable data processing pipelines, transforming input through multiple steps, and composing small,

is
associative,
so
(f
andThen
g)
andThen
h
equals
f
andThen
(g
andThen
h).
Function
composition
like
this
preserves
the
input-output
behavior
while
creating
new,
reusable
pipelines
of
transformations.
interface
exposes
andThen,
so
you
can
create
a
composed
function
by
chaining
two
or
more
single-argument
functions.
For
example,
if
addOne
maps
x
to
x
+
1
and
timesTwo
maps
x
to
x
*
2,
then
addOne.andThen(timesTwo)
applied
to
3
yields
8.
In
Scala,
Function1
instances
provide
an
andThen
method
to
achieve
the
same
effect,
enabling
concise
pipelines
of
simple
transformations.
reusable
functions
to
form
more
complex
behavior
without
writing
explicit
intermediate
variables.
andThen
emphasizes
the
order
of
application,
which
is
critical
for
correct
results
and
clear
code
semantics.
See
also:
compose.