Created
April 4, 2012 12:57
-
-
Save timyates/2300897 to your computer and use it in GitHub Desktop.
Composing functions in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
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)) }
}
Is the Function1
extension for function compose still needed or has it become part of the standard library?
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
The compose method can be written:
Which is a bit less typing ;-)