Kotlin顶级功能范围和阴影
比方说,我写了一个包含以下代码的Kotlin包:
package CoolWithATwist // code that solves the TSP in linear time followed by this: fun <T> println(x: T) { kotlin.io.println(x) haltAndCatchFire() // or any annoying/destructive function }
如果包是以字节码的形式分发的,我是否正确地假设Kotlin的规则是根据文档默认导入标准库模块,然后导入另一个模块,比如CoolWithATwist,实际上会影响标准库自动包含的println函数和因此上面的代码会执行应该用户实际调用println?
什么是检测这个最好的方法,因为Kotlin编译器不会警告全局函数的遮蔽,也不必警告你实际调用了哪个函数,IntelliJ Idea(截至版本1.1.3)的Kotlin插件,或者据我所知,Android Studio对此有何评论?
假设您在源文件夹中有以下类:
kotlin | |---- CoolWithATwist | | | |--- function.kt which contains your own println() function | | | |--- test1.kt (no imports) | | | |--- test2.kt (import kotlin.io.println) | | | |--- test.kt (import kotlin.io.*) | | | |___ NestedPackage | | | |___ test3.kt (no imports) | |____ main.kt
main.kt
, test2.kt
和test3.kt
将直接使用kotlin.io.println
。
test1.kt
将使用包顶层函数println
。
test.kt
将使用包顶层函数println
因为明星导入语句优先级低于包顶级范围。
这意味着kotlin中函数find的策略是不冒泡的,只能在本身封装中找到顶层函数。 查找策略的顺序是: local
> enclosing
> function
> class
> script
> import statement
> package top-level
> star import statement
> kotlin top-level
。
您可以简单地在调用站点函数中使用CTRL+B
/ CTRL+ALT+B
/ F4
,然后跳转到函数实际调用的源代码,例如:
fun foo(){ println("bar"); // ^--- move the cursor here and press `CTRL+B`/`CTRL+ALT+B`/`F4` }