Returning a Recursive Function from another Kotlin Function

Viewed 187

This is Kotlin equivalent of function taken from the Scala MOOC on Coursera. It returns a function that applies a given mapper(f) on a range(a..b)

fun sum(f: (Int) -> Int): (Int, Int) -> Int {
    fun sumF(a: Int, b: Int): Int =
            if (a > b) 0
            else f(a) + sumF(a + 1, b)
    return sumF
}

But IntelliJ shows these errors. How can I return the function from here. enter image description here

2 Answers

You have to use :: to express it as a function reference.

fun sum(f: (Int) -> Int): (Int, Int) -> Int {
    fun sumF(a: Int, b: Int): Int =
            if (a > b) 0
            else f(a) + sumF(a + 1, b)
    return ::sumF
}
Related