Higher-order function and recursive call

Hi , I want to implement a function, that returns a function with recursive call on itself. An Example: recursive calculation of compound interest

fun interest(end: Double, inc: Double) = {(start: Double, i: Int) ->   if(start >= end) i   else // here i want to call the function }

a simple function that works now is

fun interest(start: Double, end: Double, inc: Double, i: Int = 0): Int {   if(start >= e) return i   else return interest(start + start * inc / 100,end, inc, i + 1) }

so the best looking code would be

fun interest(end: Double, inc: Double) = {(start: Double, i: Int = 0) ->   if(start >= end) i   else (start + start * inc / 100, i + 1) } val f = interest(2000, 1)

f(1000)
f(500)


Here are two things, that are not working right now:

  1. default value
  2. recursive call

Kotlin can't do what you want exactly, but I think you can get close with a named local function

Thx for the hint with the local function.

This is a solution i’m happy with:

``

fun interest(end: Double, inc: Double) : (Double) -> Int{
  fun interest(start: Double, i: Int): Int {
  if(start >= end) i
  else interest(start + start * inc / 100, i + 1)
  }
  return {(start: Double): Int -> interest(start, 0)}
}

val f = interest(2000.0, 1.0)
println(f(1000.0))
println(f(500.0))

You can make it a bit shorter by removing the type annotations on the return line:

``

  return {start -> interest(start, 0)}