Skip to content

Function composition

Mario Arias edited this page Jun 5, 2017 · 6 revisions

Function composition is a technique that let us build new functions using existing functions as building blocks. Function composition is the base for more complex functional patterns

forwardCompose or andThen

The forwardCompose (you can use andThen also, andThen is an alias for forwardCompose) extension function join two functions, using the result of the first function as parameter of the second one

import org.funktionale.composition.*

private val add5 = {(i: Int)-> i + 5 }
private val multiplyBy2 = {(i: Int)-> i * 2 }

@Test fun testAndThen() {
  val add5andMultiplyBy2 = add5 forwardCompose multiplyBy2 // add5 andThen multiplyBy2
  assertEquals(add5andMultiplyBy2(2), 14) //(2 + 5) * 2
}

These extensions are also available for functions without parameters

compose

The compose extension function is the exact opposite of andThen, using the result of the second function as parameter of the first one

@Test fun testCompose() {
  val multiplyBy2andAdd5 = add5 compose multiplyBy2
  assertEquals(multiplyBy2andAdd5(2), 9) // (2 * 2) + 5
}
Clone this wiki locally