Search code examples
functionkotlinrecursionmutual-recursionlocal-functions

Is Mutual Recursion Supported in Kotlin?


I stumbled upon an old question from 8 years ago (Kotlin: Tail recursion for mutually recursive functions), which discusses tail recursion in Kotlin. However, my concern is with mutual recursion for functions.

When attempting to use code similar to the provided example, I encountered an error stating that 'foo' is not declared. Has Kotlin introduced any updates or features that support mutual recursion? Is there a decorator or alternative approach that enables mutual recursion in Kotlin?

fun match(xs: Deque): Boolean {
    fun boo(xs: Deque): Boolean {
        ...
        return ... foo(...)
    }

    fun foo(xs: Deque): Boolean {
        ...
        return ... boo(...)
    }

    return boo(xs)
}
...

Error: Unresolved reference: function name


Solution

  • Leviathan's answer explains why you get this error.

    If you really want to define both functions locally, you can do so by forward-declaring foo as a variable of the required function type, and then assigning it to a function body that calls boo after boo is declared. Like this:

    fun match(xs: Deque): Boolean {
    
        lateinit var foo: (Deque) -> Boolean
    
        fun boo(xs: Deque): Boolean {
            ...
            return ... foo(...)
        }
    
        foo = fun(xs: Deque): Boolean {
            ...
            return ... boo(...)
        }
    
        return boo(xs)
    }