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.
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.
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!
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.
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
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With