Kotlin顶级功能范围和阴影

And*_*rej 4 scope function 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
}
Run Code Online (Sandbox Code Playgroud)

如果包以字节码形式分发,我是否正确假设Kotlin关于根据文档默认导入标准库模块的规则以及随后导入另一个模块(如CoolWithATwist)实际上会影响标准库自动包含的println函数和因此,如果用户实际调用println,上面的代码将执行?

检测这个的最佳方法是什么,因为Kotlin编译器不会警告阴影全局函数或者必须明确命名你实际调用的函数,IntelliJ Idea上的Kotlin插件(版本1.1.3)或者,就我所知,安卓工作室,对它说什么呢?

hol*_*ava 5

假设您的源文件夹中包含以下类:

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 
Run Code Online (Sandbox Code Playgroud)

main.kt,test2.kt并且test3.kt会使用kotlin.io.println直接.

test1.kt使用所述包顶级函数意愿println.

由于星级导入语句优先级低于包顶级范围,因此test.kt将使用包顶级函数println.

这意味着kotlin中的函数查找策略没有冒泡,只能找到自身包中的顶级函数.和查找策略顺序是: 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`
}
Run Code Online (Sandbox Code Playgroud)