簡體   English   中英

Kotlin頂級功能范圍和陰影

[英]Kotlin top-level function scopes & shadowing

假設我寫了一個包含以下代碼的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上的Kotlin插件(版本1.1.3)或者,就我所知,安卓工作室,對它說什么呢?

假設您的源文件夾中包含以下類:

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.kttest2.kttest3.kt將直接使用kotlin.io.println

test1.kt將使用包頂級函數println

test.kt將使用包頂級函數println因為星型import語句優先級低於包頂級范圍。

這意味着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`
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM