Skip to content

Instantly share code, notes, and snippets.

@timyates
Created April 4, 2012 12:57
Show Gist options
  • Select an option

  • Save timyates/2300897 to your computer and use it in GitHub Desktop.

Select an option

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

timyates commented Apr 5, 2012

Copy link
Copy Markdown
Author

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
Copy Markdown

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

russel commented May 18, 2016

Copy link
Copy Markdown

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

@sksamuel

sksamuel commented Jun 9, 2016

Copy link
Copy Markdown

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