Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin top-level function scopes & shadowing

Let's say I write a Kotlin package containing the following code:

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
}

Should the package be distributed in bytecode form, am I correct in assuming that Kotlin's rules on default importing of standard library modules as per the documentation and that subsequently importing another module such as CoolWithATwist will in fact shadow the standard library auto-included println function and thus the above code will execute should the user actually call println?

What is the best way of detecting this since Kotlin compiler doesn't warn about shadowing global functions or about having to explicitly name which function you're actually calling, nor does the Kotlin plugin on IntelliJ Idea (as of version 1.1.3) or, to the best of my Knowledge, Android Studio, say anything about it?

like image 301
Andrej Avatar asked Mar 09 '23 17:03

Andrej


1 Answers

let's say you have the following classes in your source folders:

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 

the main.kt, test2.kt and test3.kt will using kotlin.io.println directly.

the test1.kt will using the package top-level function println.

the test.kt will using the package top-level function println since the star import statement priority is lower than package top-level scope.

which means the function find strategy in kotlin is not bubbled, only find the top-level function in itself package. and the find strategy order is: local > enclosing > function > class > script > import statement > package top-level > star import statement > kotlin top-level.

you can simply using CTRL+B/CTRL+ALT+B/F4 at the call-site function, then you can jump to the source code which the function was actually called,for example:

fun foo(){
   println("bar");
   // ^--- move the cursor here and press `CTRL+B`/`CTRL+ALT+B`/`F4`
}
like image 157
holi-java Avatar answered Mar 16 '23 08:03

holi-java