Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Kotlin Command-Line Compilation

Kotlin Command-Line Compilation and REPL

You can write Kotlin without installing an IDE; the official kotlinc compiler is enough to compile, package, and run your code.

This article covers installing kotlinc, common options, the interactive REPL, and .kts script mode.


Installing kotlinc

kotlinc is Kotlin's command-line compiler, distributed with the Kotlin release.

Different systems have different installation methods; pick one. After installation, the command is added to PATH.

Method Supported Systems Install Command
SDKMAN! macOS / Linux / WSL sdk install kotlin
Homebrew macOS brew install kotlin
MacPorts macOS sudo port install kotlin
Manual Download Cross-platform Download the zip from GitHub Releases, extract it, and configure PATH

SDKMAN! is the most hassle-free approach, making installation and version switching easy.



$ curl -s https://get.sdkman.io | bash

$ source "$HOME/.sdkman/bin/sdkman-init.sh"

$ sdk install kotlin



Downloading: kotlin 2.2.0

In progress...

Installing: kotlin 2.2.0

Done installing!



Setting kotlin 2.2.0 as default.

When downloading manually, open the official releases page and choose the latest version; do not copy the hard-coded old version numbers from outdated tutorials.

Download address:https://github.com/JetBrains/kotlin/releases/latest

After extracting, just add the kotlinc/bin directory to PATH in your environment variables.



$ export PATH="$PATH:/opt/kotlinc/bin"



# Put the line above into ~/.zshrc or ~/.bashrc, and it will take effect permanently after restarting the terminal.

Note:Kotlin 2.2 requires JDK 8 or later. Before installing kotlinc, run java -version to confirm the JDK is ready.


Verify the installation

After installation, use the -version option to confirm the version.



$ kotlinc -version

info: kotlinc-jvm 2.2.0 (JRE 17.0.11+9)

kotlinc-jvm in the output means the JVM backend is in use, and the number in parentheses is the JRE version running the compiler.

If you see "command not found", PATH is not configured correctly.


Compiling and Running Your First Program

First prepare the simplest source file; the file name must use the .kt extension.

Example

// File path: hello.kt

fun main

(

)

{

    println

(

"Hello, Runoob!"

)

           

// Print a line of text

    println

(

"Welcome to www.runoob.com"

)

}

Use the following command to compile it into a directly runnable jar.



$ kotlinc hello.kt -include-runtime -d hello.jar

$ java -jar hello.jar



Hello, Runoob!

欢迎来到 www.runoob.com

The first command compiles and packages the source, and the second runs the resulting jar with the JVM.


The -d and -include-runtime Options

These two options are the most commonly used in command-line compilation; understanding them avoids the "class not found when running the jar" problem.

Parameters Purpose Description
-d Specify the Output Location When followed by a directory name, it outputs class files; when followed by a name ending in .jar, it outputs a jar
-include-runtime Package the Kotlin Runtime Bundle kotlin-stdlib into the jar so it can run standalone

Without -include-runtime, the jar contains only your own classes, and you must put the standard library on the classpath at runtime.

When compiling without packaging, point -d at a directory.



$ kotlinc hello.kt -d out



$ ls out

HelloKt.class        # 顶层 main 函数所在的类,由文件名加 Kt 构成

The class file naming rule matters: top-level declarations in hello.kt are compiled into the HelloKt class.


Running the Generated Jar

Once packaged as a jar, run it with java -jar.



$ kotlinc hello.kt -include-runtime -d hello.jar

$ java -jar hello.jar



Hello, Runoob!

欢迎来到 www.runoob.com

If you forget -include-runtime at compile time, running will throw NoClassDefFoundError: kotlin/jvm/internal/Intrinsics.

In that case, either repackage it or manually add the standard library to the classpath in the java command.



$ java -cp hello.jar:kotlin-stdlib.jar HelloKt

On Windows the classpath separator is a semicolon; on Linux and macOS it is a colon.


Compiling into a Library

If this code is a utility library for others to call, you should not bundle the runtime, or it will conflict with the caller's standard library.

In that case, omit -include-runtime to produce a jar containing only your classes.

Example

// File path: Site.kt

// A simple utility library

package

com.runoob

fun buildWelcome

(

name

:

String

)

:

String

=

"Welcome to $name (www.runoob.com)"

fun main

(

)

{

    println

(

buildWelcome

(

"Runoob Tutorial"

)

)

}

Compile it as a library and run it with the kotlin command, which automatically includes the standard library.



$ kotlinc Site.kt -d site.jar

$ kotlin -classpath site.jar com.runoob.SiteKt



欢迎访问 Runoob Tutorial(www.runoob.com)

-classpath can also be shortened to -cp, followed by a jar path or directory.

If Java code needs to call it, simply add this jar to the Java project's classpath.


The REPL Interactive Interpreter

Typing kotlinc with no arguments enters the interactive interpreter, the REPL.

REPL stands for Read-Eval-Print Loop: you enter a line and it runs immediately, which is great for verifying syntax.



$ kotlinc

Welcome to Kotlin version 2.2.0 (JRE 17.0.11+9)

Type :help for help, :quit for quit

>>> val siteName = "Runoob Tutorial"

>>> println("欢迎访问 $siteName")

欢迎访问 Runoob Tutorial

>>> println("网址:www.runoob.com".uppercase())

网址:WWW.RUNOOB.COM

>>> :quit

Type :quit or press Ctrl+D to exit the REPL.

Variables persist in the REPL, so you can keep using values you defined earlier.

Tip:The REPL compiles only the snippet you enter each time, so you cannot write a full multi-line class definition; complex code is better placed in a .kt file.


Script Mode and .kts Files

Kotlin also supports script mode, where the source file extension is .kts and top-level code is executed directly.

Scripts do not need a main function and are written much like Python scripts.

Example

// File path: hello.kts

// Script mode: no main function is needed; top-level code runs directly

val siteName

=

"Runoob Tutorial"

val url

=

"www.runoob.com"

println

(

"Hello, $siteName!"

)

println

(

"Site address: $url"

)

println

(

"Name length: ${siteName.length}"

)

Use the -script option to run a script file.



$ kotlinc -script hello.kts



Hello, Runoob Tutorial!

站点地址:www.runoob.com

名称长度:4

Script mode also supports receiving command-line arguments, accessible through the args array.

Example

// File path: greet.kts

// Read command-line arguments and print them

val name

=

if

(

args.

isNotEmpty

(

)

)

args

[

0

]

else

"Runoob"

println

(

"Hello, $name! Welcome to www.runoob.com"

)



$ kotlinc -script greet.kts Runoob Tutorial



你好,Runoob Tutorial!欢迎访问 www.runoob.com

If Kotlin is already installed via SDKMAN!, you can also give the script execute permission and use #!/usr/bin/env kotlinc -script as the shebang line.


Common options

The table below summarizes the most commonly used kotlinc options, which are enough for everyday development.

Option Purpose Example
-version Show the compiler version kotlinc -version
-d Specify the output directory or jar file name kotlinc hello.kt -d hello.jar
-include-runtime Bundle the Kotlin runtime into the jar kotlinc hello.kt -include-runtime -d hello.jar
-classpath / -cp Specify dependency jars or directories kotlinc main.kt -cp libs/util.jar -d out
-jvm-target Specify the target bytecode version kotlinc hello.kt -jvm-target 17 -d out
-script Run a .kts file in script mode kotlinc -script hello.kts
-nowarn Suppress warning messages kotlinc hello.kt -nowarn -d out
-Werror Treat warnings as errors kotlinc hello.kt -Werror -d out

-Werror is useful in CI pipelines because it prevents code with warnings from being merged.


Common questions

Most errors seen in command-line compilation are related to paths and the classpath.

error: could not find or load main class

It means java -jar found the wrong entry class, or -include-runtime was omitted during packaging.

First run jar tf hello.jar to see whether the jar contains a kotlin directory.

warning: classpath entry points to a non-existent location

The classpath contains a path that does not exist; check that the jar file name and relative paths are correct.

Slow Compilation

Every kotlinc invocation starts a JVM; for large numbers of scripts, consider switching to Gradle incremental compilation.

Garbled Chinese Text in the Terminal

Make sure the terminal encoding is UTF-8; on Windows you can run chcp 65001 to switch the code page.