Kotlin 使用命令行编译
系统讲解 kotlinc 命令行编译器的安装与版本验证、-d 与 -include-runtime 参数差异、可执行 jar 与纯工具库 jar 构建、REPL 交互式解释器、.kts 脚本模式以及常用选项与排错。
学完这一章,你能够
- 系统讲解 kotlinc 命令行编译器的安装与版本验证、-d 与 -include-runtime 参数差异、可执行 jar 与纯工具库 jar 构建、REPL 交互式解释器、.kts 脚本模式以及常用选项与排错。
安装 kotlinc 与验证工具链
即使不安装 IDE,官方分发的命令行编译器 `kotlinc` 也足以完成 Kotlin 源码编译、打包 jar、运行交互式 REPL 与执行 `.kts` 脚本。安装渠道支持 SDKMAN!(推荐,适合 macOS/Linux/WSL 快速安装与切换版本)、Homebrew、MacPorts 或从 GitHub Releases(https://github.com/JetBrains/kotlin/releases/latest)手动下载最新压缩包解压后将 `kotlinc/bin` 加入环境变量 `PATH`(切勿照抄旧资料写死的老版本号)。运行 Kotlin 2.2 编译器前需通过 `java -version` 确认本机已就绪 JDK 8 及以上环境。
安装完毕后执行 `kotlinc -version` 检查版本输出,其中的 `kotlinc-jvm` 表示当前为 JVM 后端,括号内显示驱动编译器运行的 JRE 版本;若终端报 `command not found`,说明 `PATH` 环境变量尚未生效或路径有误。
编译可执行 jar、-d 与 -include-runtime 以及工具库打包
准备扩展名为 `.kt` 的源文件(如 `hello.kt`)后,执行 `kotlinc hello.kt -include-runtime -d hello.jar` 即可编译并生成包含运行时标准库的可执行 jar,随后用 `java -jar hello.jar` 启动。参数 `-d` 决定输出形态:指向 `.jar` 路径则打包为 jar,指向普通目录(如 `-d out`)则直接输出 `.class` 字节码文件,且顶层声明会编译进 `HelloKt.class`。
若打包可执行 jar 时漏写 `-include-runtime`,`java -jar` 会因缺失标准库而抛出 `NoClassDefFoundError: kotlin/jvm/internal/Intrinsics`。此时要么重新加 `-include-runtime` 打包,要么使用 `java -cp` 手动将 `kotlin-stdlib.jar` 加入 classpath 并指定入口类 `HelloKt`(注意 Windows 下 classpath 分隔符为分号 `;`,Linux/macOS 为冒号 `:`)。
相反,若编写供其他项目复用的工具库(例如 `package com.mbsky` 下的 `Site.kt`),则不应添加 `-include-runtime`,以免把运行时打入库包引发依赖冲突。直接执行 `kotlinc Site.kt -d site.jar` 得到纯类 jar 后,可通过自动挂载标准库的 `kotlin -classpath site.jar com.mbsky.SiteKt`(`-classpath` 可简写为 `-cp`)运行,也可直接加入 Java 项目 classpath 供 Java 调用。
REPL 交互式解释器与 .kts 脚本模式
直接运行不带参数的 `kotlinc` 将启动交互式解释器 REPL(Read-Eval-Print Loop),输入一行表达式即可立即求值,且会话中定义的变量会持续保留供后续语句复用。退出时输入 `:quit` 或按 Ctrl+D。由于 REPL 每次仅即时编译当前输入片段,不适合编写复杂的多行类体系,较长代码仍应保存到 `.kt` 文件。
Kotlin 同时支持以 `.kts` 为扩展名的脚本模式:无需编写 `main` 函数,顶层语句会按顺序直接执行,使用 `kotlinc -script hello.kts` 即可运行。脚本还可通过内置 `args` 数组读取命令行参数(如 `kotlinc -script greet.kts 蓝色天空网`);在类 Unix 环境中若通过 SDKMAN! 安装了 Kotlin,还可赋予 `.kts` 文件可执行权限并在首行添加 `#!/usr/bin/env kotlinc -script` 作为 shebang。
kotlinc 常用选项与命令行排错
日常命令行编译最常使用的选项包括 `-version`、`-d`、`-include-runtime`、`-classpath`/`-cp`、`-jvm-target`、`-script`、`-nowarn` 与 `-Werror`。其中 `-Werror` 会将编译警告升级为构建错误,在 CI 流水线中非常有助于阻止带隐患代码合入。
遇到命令行报错时可按现象快速定位:报 `error: could not find or load main class` 多为入口类指定有误或漏加 `-include-runtime`,可用 `jar tf hello.jar` 检查包内是否含有 `kotlin/` 目录;报 `warning: classpath entry points to a non-existent location` 需核对 jar 名称与相对路径;若感觉编译偏慢,是因为每次调用 `kotlinc` 都需冷启动一次 JVM,多文件项目应改用 Gradle 增量编译;若终端输出中文乱码,需统一终端编码为 UTF-8(Windows 命令行可执行 `chcp 65001`)。
kotlinc 跨平台安装方式汇总
| 方式 | 适用系统 | 安装命令 |
|---|---|---|
| SDKMAN! | macOS / Linux / WSL | sdk install kotlin |
| Homebrew | macOS | brew install kotlin |
| MacPorts | macOS | sudo port install kotlin |
| 手动下载 | 全平台 | 从 GitHub Releases 下载 zip 解压并配置 PATH |
-d 与 -include-runtime 核心参数说明
| 参数 | 作用 | 说明 |
|---|---|---|
| -d | 指定输出位置 | 后接目录名时生成 .class 文件;后接 .jar 文件名时打包为 jar。 |
| -include-runtime | 打包 Kotlin 运行时 | 将 kotlin-stdlib 一并打入 jar,使其可直接通过 java -jar 独立运行。 |
kotlinc 常用命令行选项速查
| 选项 | 作用 | 示例 |
|---|---|---|
| -version | 显示编译器版本 | kotlinc -version |
| -d | 指定输出目录或 jar 文件名 | kotlinc hello.kt -d hello.jar |
| -include-runtime | 把 Kotlin 运行时打包进 jar | kotlinc hello.kt -include-runtime -d hello.jar |
| -classpath / -cp | 指定依赖的 jar 或目录 | kotlinc main.kt -cp libs/util.jar -d out |
| -jvm-target | 指定目标字节码版本 | kotlinc hello.kt -jvm-target 17 -d out |
| -script | 以脚本模式运行 .kts 文件 | kotlinc -script hello.kts |
| -nowarn | 不输出警告信息 | kotlinc hello.kt -nowarn -d out |
| -Werror | 把警告当作错误处理 | kotlinc hello.kt -Werror -d out |
离线校验 kotlinc 参数解析、jar/类目录输出、Intrinsics 异常与 REPL/.kts 模型
"""Offline Kotlin 2.x semantic verifier for Chapter 05 (command-line)."""
import json
import sys
VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"
def parse_kotlinc_args(argv: list[str]) -> dict:
"""Deterministic CLI flag parser modeling kotlinc options."""
result = {
"version": False,
"output": None,
"output_kind": None,
"include_runtime": False,
"classpath": None,
"jvm_target": None,
"script": None,
"nowarn": False,
"werror": False,
"sources": [],
}
i = 0
while i < len(argv):
tok = argv[i]
if tok == "-version":
result["version"] = True
elif tok == "-include-runtime":
result["include_runtime"] = True
elif tok == "-nowarn":
result["nowarn"] = True
elif tok == "-Werror":
result["werror"] = True
elif tok == "-d":
i += 1
out = argv[i]
result["output"] = out
result["output_kind"] = "jar" if out.endswith(".jar") else "directory"
elif tok in ("-classpath", "-cp"):
i += 1
result["classpath"] = argv[i]
elif tok == "-jvm-target":
i += 1
result["jvm_target"] = argv[i]
elif tok == "-script":
i += 1
result["script"] = argv[i]
else:
result["sources"].append(tok)
i += 1
return result
def file_to_facade(package: str | None, filename: str) -> str:
stem = filename[:-3] if filename.endswith(".kt") else filename
cls = stem[0].upper() + stem[1:] + "Kt"
return f"{package}.{cls}" if package else cls
def simulate_jar_run(include_runtime: bool, manual_stdlib_cp: bool) -> dict:
if include_runtime or manual_stdlib_cp:
return {"ok": True, "error": None}
return {"ok": False, "error": "NoClassDefFoundError: kotlin/jvm/internal/Intrinsics"}
def run_cases() -> list[dict]:
cases: list[dict] = []
# Case 1: Installation methods & -version flag
install_methods = {
"SDKMAN!": "sdk install kotlin",
"Homebrew": "brew install kotlin",
"MacPorts": "sudo port install kotlin",
"手动下载": "GitHub Releases zip + PATH",
}
parsed_ver = parse_kotlinc_args(["-version"])
actual_1 = {
"install_method_count": len(install_methods),
"version_flag": parsed_ver["version"],
"min_jdk": 8,
}
expected_1 = {
"install_method_count": 4,
"version_flag": True,
"min_jdk": 8,
}
cases.append({
"name": "kotlinc_install_and_version_flag",
"summary": "Verify four kotlinc install channels, -version flag parsing, and JDK 8+ prerequisite.",
"expected": expected_1,
"actual": actual_1,
"passed": actual_1 == expected_1,
})
# Case 2: -d (jar vs directory), -include-runtime, facade class naming, and classpath separator
fat_jar = parse_kotlinc_args(["hello.kt", "-include-runtime", "-d", "hello.jar"])
class_dir = parse_kotlinc_args(["hello.kt", "-d", "out"])
lib_jar = parse_kotlinc_args(["Site.kt", "-d", "site.jar"])
actual_2 = {
"fat_jar_kind": fat_jar["output_kind"],
"fat_jar_run": simulate_jar_run(fat_jar["include_runtime"], False),
"missing_runtime_run": simulate_jar_run(False, False),
"manual_cp_run": simulate_jar_run(False, True),
"dir_output_kind": class_dir["output_kind"],
"hello_facade": file_to_facade(None, "hello.kt"),
"site_facade": file_to_facade("com.mbsky", "Site.kt"),
"lib_has_runtime": lib_jar["include_runtime"],
"cp_separators": {"windows": ";", "posix": ":"},
}
expected_2 = {
"fat_jar_kind": "jar",
"fat_jar_run": {"ok": True, "error": None},
"missing_runtime_run": {"ok": False, "error": "NoClassDefFoundError: kotlin/jvm/internal/Intrinsics"},
"manual_cp_run": {"ok": True, "error": None},
"dir_output_kind": "directory",
"hello_facade": "HelloKt",
"site_facade": "com.mbsky.SiteKt",
"lib_has_runtime": False,
"cp_separators": {"windows": ";", "posix": ":"},
}
cases.append({
"name": "kotlinc_jar_dir_runtime_and_facade",
"summary": "Model -d directory/jar outputs, -include-runtime behavior, Intrinsics error, and FileKt facade naming.",
"expected": expected_2,
"actual": actual_2,
"passed": actual_2 == expected_2,
})
# Case 3: REPL stateful session & .kts script execution with args
repl_env: dict[str, str] = {}
repl_env["siteName"] = "蓝色天空网"
repl_out_1 = f"欢迎访问 {repl_env['siteName']}"
repl_out_2 = "网址:www.mbsky.com".upper()
script_parsed = parse_kotlinc_args(["-script", "greet.kts", "蓝色天空网"])
args = script_parsed["sources"]
greet_name = args[0] if args else "Kotlin"
actual_3 = {
"repl_lines": [repl_out_1, repl_out_2],
"repl_exit_cmd": ":quit",
"script_file": script_parsed["script"],
"script_greeting": f"你好,{greet_name}!欢迎访问 www.mbsky.com",
"default_greeting": "你好,Kotlin!欢迎访问 www.mbsky.com",
}
expected_3 = {
"repl_lines": ["欢迎访问 蓝色天空网", "网址:WWW.MBSKY.COM"],
"repl_exit_cmd": ":quit",
"script_file": "greet.kts",
"script_greeting": "你好,蓝色天空网!欢迎访问 www.mbsky.com",
"default_greeting": "你好,Kotlin!欢迎访问 www.mbsky.com",
}
cases.append({
"name": "repl_session_and_kts_script_args",
"summary": "Simulate persistent REPL variable binding and .kts script argument passing.",
"expected": expected_3,
"actual": actual_3,
"passed": actual_3 == expected_3,
})
# Case 4: Full common option flags (-cp, -jvm-target, -nowarn, -Werror)
ci_cmd = parse_kotlinc_args(["main.kt", "-cp", "libs/util.jar", "-jvm-target", "17", "-Werror", "-d", "out"])
quiet_cmd = parse_kotlinc_args(["hello.kt", "-nowarn", "-d", "out"])
actual_4 = {
"cp": ci_cmd["classpath"],
"jvm_target": ci_cmd["jvm_target"],
"werror": ci_cmd["werror"],
"nowarn": quiet_cmd["nowarn"],
}
expected_4 = {
"cp": "libs/util.jar",
"jvm_target": "17",
"werror": True,
"nowarn": True,
}
cases.append({
"name": "kotlinc_common_flags_verification",
"summary": "Verify -cp/-classpath, -jvm-target, -nowarn, and -Werror flag semantics.",
"expected": expected_4,
"actual": actual_4,
"passed": actual_4 == expected_4,
})
return cases
def main() -> None:
payload = {"version": VERSION, "cases": run_cases()}
sys.stdout.write(json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
if __name__ == "__main__":
main()
- 离线脚本确认 4 种安装渠道、-d/-include-runtime/Facade 命名与 classpath 分隔符、REPL 状态与 .kts args、以及 -cp/-jvm-target/-nowarn/-Werror 解析全部通过。
所需环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。
当前源码 SHA256:9f0ef3c5f9a97e4c8f82c59b463a0b5ac2f9e4c59275970ff5ef1a879e7d0ace
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。
ZIP SHA256:3dca3babeb44c52c629e81f8bdde9ac155765c8e6966b2f9353413fdf84eaa04
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
编译给其他项目调用的 Kotlin 工具库 jar 时,为什么通常不建议加 `-include-runtime`?
展开参考解答
因为加上 `-include-runtime` 会把整个 `kotlin-stdlib` 打包进工具库 jar,容易与调用方工程自身的 Kotlin 标准库版本产生类重复或冲突。