Does Kotlin support partial application?
There is a very nice and light library to Kotlin: org.funktionale
. In module funktionale-currying
you'll find extenstion methods to lambdas: curried()
and uncurried()
.
Example:
val add = { x: Int, y: Int -> x + y }.curried()
val add3 = add(3)
fun test() {
println(add3(5)) // prints 8
}
Out of the box, no. But it isn't too hard to do with a helper function:
fun add(a: Int, b:Int): Int {
return a + b
}
fun <A, B, C> partial2(f: (A, B) -> C, a: A): (B) -> C {
return { b: B -> f(a, b)}
}
val add1 = partial2(::add, 1)
val result = add1(2) //3
So partial2 takes a function of 2 arguments and the first argument and applies it to get a function of 1 argument. You would have to write such helpers for all arities you need.
Alternatively, you can do it with an extension method:
fun <A,B,C> Function2<A,B,C>.partial(a: A): (B) -> C {
return {b -> invoke(a, b)}
}
val abc: (Int) -> Int = (::add).partial(1)