使用前必须声明Kotlin局部函数 [英] Must Kotlin Local Functions be Declared Before Use

查看:208
本文介绍了使用前必须声明Kotlin局部函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个简单的代码示例中...

In this simple code example...

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

在语言的其他地方,使用允许定义之前的函数.但是对于局部函数,情况似乎并非如此.参考科林语言规范,有关本地功能的部分仍标记为"TODO .

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?)

推荐答案

这不是错误,而是设计的行为.

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.

这篇关于使用前必须声明Kotlin局部函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆