Reputation: 2454
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.
Upvotes: 5
Views: 223
Reputation: 147911
When a you define a named function (fun foo(...)
), you cannot use its name as an expression.
Instead, you should make a function reference of it:
return ::sumF
See also: Why does Kotlin need function reference syntax?
Upvotes: 3
Reputation: 482
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
}
Upvotes: 2