Returning a recursive function from another Kotlin function

This is Kotlin's equivalent of a function taken from Scala MOOC on Coursera. It returns a function that applies the given mapper (f) in the 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 here. enter image description here

+4
source share
2 answers

When you define a named function ( fun foo(...)), you cannot use its name as an expression.

Instead, you should make a reference to the function :

return ::sumF

See also: Why does Kotlin need link link syntax?

+3
source

You must 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
}
+2
source

Source: https://habr.com/ru/post/1688696/


All Articles