Search code examples
kotlinfunctional-programmingpartial-application

Does Kotlin support partial application?


Since Kotlin supports many concepts from functional programming, I was wondering if there is a way to do partial application of a function in Kotlin as well?

One such example of where partial application can be useful is:

// In one class
fun doSomething(cb: (a, b) -> Unit) {
    <some logic here to compute someField>
    doSomethingElse(cb.applyPartially(someField))
}

// In another class
fun doSomethingElse(cb: (b) -> Unit) {
    <some logic here to compute someOtherField>
    cb(someOtherField)
}

Solution

  • 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)