Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a Recursive Function from another Kotlin Function

Tags:

kotlin

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

like image 250
Himanshu Avatar asked Nov 03 '17 17:11

Himanshu


People also ask

How to use recursion in Kotlin?

Like other programming languages, we can use recursion in Kotlin. A function which calls itself is called as recursive function and this process of repetition is called recursion. When a function is called from main () block then it is called a normal function call.

How to mark the return type of a function in Kotlin?

Kotlin does not infer return types for functions with block bodies because such functions may have complex control flow in the body, and the return type will be non-obvious to the reader (and sometimes even for the compiler). You can mark a parameter of a function (usually the last one) with the vararg modifier: Copied!

How many values can an array return in Kotlin?

Moreover, we can use arrays and collections to return up to five values of the same type: The Kotlin limit is five because it has defined five componentN extension functions on arrays and collections. Sometimes, it’s better to define a custom type with a meaningful name.

What is the difference between component1 and component2 in Kotlin?

That is, the component1 function is the first destructured variable, the component2 function is the second variable, and so on. In Kotlin, a few types are already usable for destructuring declarations: The data classes, as they declare component functions for all their properties


1 Answers

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?

like image 181
hotkey Avatar answered Nov 03 '22 20:11

hotkey