You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何运行引用其他Kotlin文件的Kotlin脚本?

Fixing "unresolved reference" Error When Running Kotlin Script with Custom Library

Let's break down the issue and fix it step by step. The error you're seeing happens because the Kotlin script compiler doesn't automatically detect and compile adjacent Kotlin library files by default—you need to explicitly tell it where to find your experiment package code.

Here are two reliable solutions to get your script running:

Solution 1: Compile the Library First, Then Run the Script with Classpath

First, we'll compile your experiment.kt into bytecode, then reference that compiled code when running the script:

  1. Compile the library file to generate class files:

    cd kotlin-experiment
    kotlinc experiment.kt -d .
    

    This creates an experiment directory in your current folder containing the compiled class files for your sum function.

  2. Run the script with the classpath pointing to your current directory (where the compiled code lives):

    kotlinc -script Play.kts -cp .
    

    The -cp . flag tells the compiler to include the current directory in the classpath, so it can find the experiment package.

Solution 2: Directly Import the Library File in the Script

A more streamlined approach is to use the @file:Import annotation in your script to tell Kotlin to load and compile the library file automatically:

Modify your Play.kts to include the import annotation at the very top:

@file:Import("experiment.kt")
import experiment.*
println(sum(2, 2))

Now you can run the script directly with your original command, and it will work without extra steps:

kotlinc -script Play.kts

Why the Original Command Failed

By default, Kotlin scripts only process their own content. When you tried to import experiment.*, the compiler had no idea where to find that package—since it wasn't told to look at experiment.kt or any compiled code from it. Either of the above methods fixes this by explicitly including the library code in the compilation process.

内容的提问来源于stack exchange,提问作者Alex Craft

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 08:32:34