Skip to content

Instantly share code, notes, and snippets.

@timyates
Created April 4, 2012 12:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timyates/2300897 to your computer and use it in GitHub Desktop.
Save timyates/2300897 to your computer and use it in GitHub Desktop.
Composing functions in Kotlin
fun compose<T>( fa: ( T ) -> T, fb : ( T ) -> T ) : ( T ) -> T {
return { ( a : T ) : T -> fb( fa( a ) ) }
}
fun main( args : Array<String> ) {
val composed = compose<Int>( { ( a : Int ) : Int -> a + 10 }, // add 10
{ ( a : Int ) : Int -> a * 2 } ) // multiply by 2
println( composed( 2 ) ) // prints 24
}
@timyates
Copy link
Author

timyates commented Apr 5, 2012

The compose method can be written:

fun compose<T>( fa: Function1<T,T>, fb : Function1<T,T> ) : Function1<T,T> {
  return { ( a : T ) : T -> fb( fa( a ) ) }
}

Which is a bit less typing ;-)

@nousedaccount
Copy link

Or you can create Extended function for Function1

infix public fun<V, T, R> Function1<T, R>.compose(before: (V) -> T): (V) -> R {
    return { v: V -> this(before(v)) }
}

@russel
Copy link

russel commented May 18, 2016

Is the Function1 extension for function compose still needed or has it become part of the standard library?

@sksamuel
Copy link

sksamuel commented Jun 9, 2016

It should be part of the standard library if its not already.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment