Kotlin跨文件导入函数失败求助(VS Code/IDEA/Android Studio)
Kotlin跨文件调用函数报错解决方案
问题场景
目录结构:MyFun.kt 和 Main.kt 位于同一根目录下。
MyFun.kt 代码
fun sayHello() { println("Hello") }
Main.kt 错误代码
import MyFun.kt fun main() { sayHello() }
尝试过import MyFun和import MyFun.*两种导入方式,均触发报错。
Code Runner运行报错
[Running] cd "c:\Users\dov4k1n\Documents\GitHub\Other\TestImporting\" && kotlinc tempCodeRunnerFile.kt -include-runtime -d tempCodeRunnerFile.jar && java -jar tempCodeRunnerFile.jar tempCodeRunnerFile.kt:1:8: error: unresolved reference: MyFun import MyFun.kt ^ tempCodeRunnerFile.kt:4:5: error: unresolved reference: sayHello sayHello() ^ [Done] exited with code=1 in 6.588 seconds
命令行编译报错
C:\Users\dov4k1n\Documents\GitHub\Other\TestImporting>kotlinc Main.kt MyFun.kt -include-runtime -d Main.jar Main.kt:1:8: error: unresolved reference: MyFun import MyFun.kt ^
运行环境:Windows 11 64位、Kotlin 1.9.0、JDK 20、JRE 8u381 win64、VS Code搭配Code Runner插件与MathiasFrohlich的Kotlin插件,IntelliJ IDEA中出现相同错误。
解决方案
- 删除错误导入语句
Kotlin中,同一目录下的文件默认归属同一个默认包,无需手动导入。直接移除import MyFun.kt或其他错误的import语句即可。修改后的Main.kt代码:
fun main() { sayHello() }
- 编译运行规范
- 命令行编译时,必须将所有依赖的.kt文件都列入编译指令:
kotlinc Main.kt MyFun.kt -include-runtime -d Main.jar java -jar Main.jar - VS Code的Code Runner插件需配置正确,确保运行命令能识别同一目录下的依赖文件。可检查
code-runner.executorMap中的Kotlin指令,手动修改为包含所有相关.kt文件的编译命令。
补充说明
若后续文件拆分到不同包下,才需要通过包名导入。例如MyFun.kt放在com.example包中:
package com.example fun sayHello() { println("Hello") }
此时Main.kt需按包导入:
import com.example.sayHello // 或使用 import com.example.* fun main() { sayHello() }
内容的提问来源于stack exchange,提问作者Ayzat Rizatdinov
相关产品推荐
相关产品推荐

