Must Kotlin Local Functions be Declared Before Use

Viewed 602

In this simple code example...

fun testLocalFunctions() {
    aLocalFun() //compiler error: unresolved reference at aLocalFun
    fun aLocalFun() {}
    aLocalFun() //no error
}

Elsewhere in the language, using a function before definition is allowed. But for local functions, that does not appear to be the case. Refering to the Kotlin Language Specification, the section on Local Functions is still marked "TODO".

Since this sort of constraint does not hold for other types of functions (top-level and member functions), is this a bug?

(Granted, local variable declarations must occur before use, so the same constraint on local functions is not unreasonable. Is there a definitive, preferably authoritative source document that discusses this behavior?)

1 Answers

It's not a bug, it is the designed behavior.

When you use a symbol (variable, type or function name) in an expression, the symbol is resolved against some scope. If we simplify the scheme, the scope is formed by the package, the imports, the outer declarations (e.g. other members of the type) and, if the expression is placed inside a function, the scope also includes the local declarations that precede the expression.

So, you can't use a local function until it's declared just like you cannot use a local variable that is not declared up to that point: it's just out of scope.

Related