# Kotlin — User Guide

Kotlin is a concise, multiplatform programming language developed by JetBrains and contributors. It compiles to JVM bytecode, JavaScript, native binaries (via LLVM), and WebAssembly from a single language and standard library. This guide shows you how to install the Kotlin toolchain, compile and run Kotlin code from the command line, build projects with Gradle and Maven, target multiple platforms, and use the bundled compiler plugins.

> [!NOTE]
> This guide documents the Kotlin compiler and toolchain as built from the `JetBrains/kotlin` repository on the development branch for **Kotlin 2.4** (default language version `2.4`). Where a feature was introduced in an earlier release, that release is noted. The `kotlinlang.org` site hosts the always-current narrative tutorials; this guide is the source-based reference for the compiler's own command-line surface.

---

## 1. Quick Start

### 1.1 Your first program

Create a file named `hello.kt`:

```kotlin
fun main() {
    println("Hello, Kotlin!")
}
```

Compile it to a self-contained JAR and run it:

```bash
kotlinc hello.kt -include-runtime -d hello.jar
java -jar hello.jar
```

```text
Hello, Kotlin!
```

> [!TIP]
> The `-include-runtime` flag bundles the Kotlin standard library into the JAR so it runs anywhere a JVM is available, with no extra classpath setup. Omit it when you manage the `kotlin-stdlib` dependency yourself (for example, in a Gradle build).

### 1.2 Run without producing a JAR

Compile to a directory and launch with the `kotlin` runner, which locates the entry point for you:

```bash
kotlinc hello.kt -d hello/
kotlin -classpath hello/ HelloKt
```

```text
Hello, Kotlin!
```

> [!NOTE]
> A top-level `main` in `hello.kt` is compiled into a class named `HelloKt` (the file name, capitalized, with `Kt` appended). This is the class you pass to `kotlin` or `java`.

### 1.3 Evaluate an expression directly

```bash
kotlinc -e "println((1..10).sum())"
```

```text
55
```

### 1.4 Run a script

Kotlin scripts use the `.kts` extension and need no `main` function:

```kotlin
// fib.kts
fun fib(n: Int): Int = if (n < 2) n else fib(n - 1) + fib(n - 2)
println((0..10).map(::fib))
```

```bash
kotlinc -script fib.kts
```

```text
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
```

---

## 2. Installation

The command-line compiler ships as a `kotlin-compiler-<version>.zip` archive containing the `kotlinc`, `kotlinc-jvm`, `kotlinc-js`, and `kotlin` launcher scripts under a `bin/` directory. You can install it through a package manager or unpack it manually.

=== "SDKMAN! (Linux/macOS)"

    ```bash
    sdk install kotlin
    kotlinc -version
    ```

=== "Homebrew (macOS)"

    ```bash
    brew install kotlin
    kotlinc -version
    ```

=== "Manual (any OS)"

    ```bash
    # Download kotlin-compiler-<version>.zip from the GitHub Releases page,
    # then unzip and add the bin directory to your PATH:
    unzip kotlin-compiler-*.zip -d ~/kotlin
    export PATH="$PATH:~/kotlin/kotlinc/bin"
    kotlinc -version
    ```

=== "Windows (Scoop)"

    ```powershell
    scoop install kotlin
    kotlinc -version
    ```

> [!IMPORTANT]
> The command-line compiler requires a Java runtime (JRE/JDK) to execute, because `kotlinc` itself runs on the JVM. A JDK is also needed to *run* the Kotlin/JVM output you produce. Install a JDK (for example, from Eclipse Adoptium) and ensure `JAVA_HOME` points at it before using `kotlinc`.

### 2.1 Verify the installation

```bash
kotlinc -version
```

```text
info: kotlinc-jvm 2.4.0 (JRE 21.0.x+...)
```

### 2.2 Requirements

| Component | Requirement |
|-----------|-------------|
| JVM compilation & execution | A JDK; the default generated bytecode targets Java 8 (`1.8`), and JVM targets `1.8` and `9`–`26` are supported |
| Kotlin/Native | No JDK required at runtime; the compiler downloads an LLVM toolchain and platform libraries on first use |
| Kotlin/JS | Node.js (for running and testing generated JavaScript) |
| Kotlin/Wasm | A Wasm-capable runtime (a modern browser, or a `wasm-wasi` host) |
| Build tooling | Gradle (recommended) or Maven |

> [!TIP]
> For real projects, you rarely call `kotlinc` directly. Use **Gradle** or **Maven** (Section 7) so dependency resolution, incremental compilation, and multiplatform target wiring are handled for you. The command-line compiler is ideal for small programs, scripts, experiments, and understanding exactly what the build tools invoke under the hood.

---

## 3. Using the Command-Line Compiler

The Kotlin distribution provides several launchers:

| Launcher | Purpose |
|----------|---------|
| `kotlinc` | Alias for `kotlinc-jvm` — compile Kotlin to JVM bytecode |
| `kotlinc-jvm` | Compile Kotlin source to `.class` files or a `.jar` |
| `kotlinc-js` | Compile Kotlin to JavaScript |
| `kotlin` | Run compiled Kotlin (a class file, a JAR, or a script) |

A `kotlinc` invocation has the form:

```bash
kotlinc [<options>] <source files and directories>
```

Source arguments may be individual `.kt`/`.kts` files or directories, which are scanned recursively.

### 3.1 Compiling to a directory or JAR

```bash
# Compile every .kt under src/ into the classes/ directory
kotlinc src/ -d classes/

# Compile into a single runnable JAR with the runtime bundled
kotlinc src/ -include-runtime -d app.jar
```

The `-d` option (`<directory|jar>`) sets the destination. If the path ends in `.jar`, a JAR is produced; otherwise class files are written into the directory.

### 3.2 Adding libraries to the classpath

```bash
kotlinc app.kt -classpath "libs/guava.jar:libs/gson.jar" -d app.jar
```

> [!NOTE]
> `-classpath` (short form `-cp`) accepts a list of directories and JAR/ZIP archives separated by your platform's path separator (`:` on Unix/macOS, `;` on Windows).

### 3.3 Running compiled code with `kotlin`

The `kotlin` runner inspects its argument and decides how to run it. You can force the mode:

```bash
kotlin -classpath app.jar MainKt          # guess (default)
kotlin -howtorun jar app.jar              # run as a JAR
kotlin -howtorun classfile -cp out/ MainKt # run a compiled class
kotlin -howtorun script analysis.kts      # run as a script
```

| `kotlin` option | Effect |
|-----------------|--------|
| `-classpath` / `-cp` `<path>` | Classpath for the program being run |
| `-howtorun` `<mode>` | One of `guess` (default), `classfile`, `jar`, `script`, or `.<ext>` |
| `-no-stdlib` | Do not add the Kotlin stdlib to the run classpath |
| `-no-reflect` | Do not add `kotlin-reflect` to the run classpath |
| `-version` | Print the runner version |
| `-help` / `-h` | Print runner usage |

> [!IMPORTANT]
> The `kotlin` runner needs to know where the distribution lives; the launcher script sets the `kotlin.home` system property for you. If you invoke the runner JAR directly, you must pass `-Dkotlin.home=<path>`, or it exits with `error: no kotlin.home system property was passed`.

### 3.4 The REPL

Starting `kotlinc` with no source files opens an interactive shell:

```bash
kotlinc
```

```text
Welcome to Kotlin version 2.4.0 (JRE 21.0.x)
Type :help for help, :quit for quit
>>> val x = 21
>>> x * 2
res2: kotlin.Int = 42
```

> [!WARNING]
> The dedicated `-Xrepl` flag is **deprecated**. Launch the REPL by running `kotlinc` with no input files instead.

---

## 4. Compiler Options Reference

Kotlin distinguishes **standard** options (stable, documented, safe for everyday use) from **advanced** options, which begin with `-X`. Advanced options control experimental behavior and may change between releases. Run `kotlinc -help` for standard options and `kotlinc -X` for the advanced set.

### 4.1 Common options (all targets)

These options apply to every compilation target.

| Option | Value | Description |
|--------|-------|-------------|
| `-help` / `-h` | — | Print a synopsis of standard options |
| `-X` | — | Print a synopsis of advanced options |
| `-version` | — | Display the compiler version |
| `-verbose` | — | Enable verbose logging output |
| `-nowarn` | — | Don't generate any warnings |
| `-Werror` | — | Report an error if there are any warnings |
| `-Wextra` | — | Enable extra (opt-in) checkers; introduced in 2.1 |
| `-language-version` | `<version>` | Provide source compatibility with the specified version of Kotlin |
| `-api-version` | `<version>` | Allow using declarations only from the specified version of bundled libraries |
| `-kotlin-home` | `<path>` | Path to the Kotlin compiler home directory used to discover runtime libraries |
| `-progressive` | — | Enable progressive mode: deprecations and bug fixes for unstable code take effect immediately. Progressive code stays backward compatible |
| `-script` | — | Evaluate the given Kotlin script (`*.kts`) file |
| `-opt-in` | `<fq.name>` | Enable API usages that require an opt-in requirement marker with the given fully qualified name |
| `-P` | `plugin:<id>:<name>=<value>` | Pass an option to a compiler plugin |
| `-Xplugin` | `<path>` | Load compiler plugins from the given classpath |

> [!TIP]
> Use `-progressive` in new code to adopt the strictest, most future-proof behavior early. Because progressive-mode code remains backward compatible, you can turn it on without breaking consumers who compile in the default mode.

#### Selected advanced common options

| Option | Description |
|--------|-------------|
| `-Xmulti-platform` | Enable language support for multiplatform projects (`expect`/`actual`) |
| `-Xexplicit-api={strict\|warning}` | Require explicit visibility and return types on all public API declarations — recommended for libraries |
| `-Xsuppress-version-warnings` | Suppress warnings about outdated, inconsistent, or experimental language/API versions |
| `-Xwarning-level=<NAME>:(error\|warning\|disabled)` | Set the severity of a specific warning (granular `-Werror`/`-nowarn`) |
| `-Xcontext-parameters` | Enable experimental context parameters (introduced 2.2) |
| `-Xwhen-guards` | Enable experimental `when` guards |
| `-Xno-inline` | Disable function inlining |
| `-Xrender-internal-diagnostic-names` | Render the internal names of warnings and errors (useful with `-Xwarning-level`) |

> [!CAUTION]
> Options beginning with `-XX` (for example `-XXLanguage`, `-XXlenient-mode`) are internal and are **not** intended for production use. They can change or be removed without notice and may slow down or destabilize the compiler.

### 4.2 Kotlin/JVM options

| Option | Value | Description |
|--------|-------|-------------|
| `-d` | `<directory\|jar>` | Destination for generated class files (or a JAR) |
| `-classpath` / `-cp` | `<path>` | Directories and JAR/ZIP archives to search for user class files |
| `-include-runtime` | — | Include the Kotlin runtime in the resulting JAR |
| `-jdk-home` | `<path>` | Use a custom JDK from this location instead of `JAVA_HOME` |
| `-no-jdk` | — | Don't automatically include the Java runtime in the classpath |
| `-no-stdlib` | — | Don't automatically include the Kotlin/JVM stdlib and reflection on the classpath |
| `-no-reflect` | — | Don't automatically include the Kotlin reflection dependency |
| `-expression` / `-e` | `<string>` | Evaluate the given string as a Kotlin script |
| `-module-name` | `<name>` | Name of the generated `.kotlin_module` file |
| `-jvm-target` | `<version>` | Target version of the generated JVM bytecode: `1.8` and `9`–`26`, default `1.8` |
| `-java-parameters` | — | Generate metadata for Java 8 reflection on method parameters |
| `-jvm-default` | `{enable\|no-compatibility\|disable}` | Control emission of JVM default methods for interface declarations. Default is `enable` (since language version 2.2) |
| `-script-templates` | `<fq.class.name[,]>` | Script definition template classes |

> [!NOTE]
> `-jvm-default` replaces the deprecated `-Xjvm-default`. Migrate `all-compatibility` → `enable`, `all` → `no-compatibility`, and `disable` → `disable`.

#### Selected advanced JVM options

| Option | Description |
|--------|-------------|
| `-Xjdk-release=<version>` | Compile against the specified JDK API version (like `javac --release`); requires JDK 9+ and also sets `-jvm-target` |
| `-Xjsr305={ignore\|strict\|warn}` | Control the behavior of JSR-305 nullability annotations |
| `-Xjspecify-annotations={ignore\|strict\|warn}` | Control the behavior of JSpecify annotations (default `strict`) |
| `-Xstring-concat={indy-with-constants\|indy\|inline}` | Code-generation scheme for string concatenation |
| `-Xlambdas={indy\|class}` | Code-generation scheme for lambdas (default `indy` on language version 2.0+) |
| `-Xsam-conversions={indy\|class}` | Code-generation scheme for SAM conversions (default `indy`) |
| `-Xbackend-threads=<N>` | Run the codegen phase in N parallel threads (`0` = one per core) |
| `-Xjvm-enable-preview` | Allow Java preview features (like `javac --enable-preview`) |
| `-Xno-call-assertions`, `-Xno-param-assertions`, `-Xno-receiver-assertions` | Suppress not-null assertions for platform-type values |
| `-Xjvm-expose-boxed` | Expose inline classes and functions to Java |

> [!TIP]
> Set `-jvm-target` to match the JDK you deploy on. To both target an older API *and* prevent accidental use of newer JDK APIs, prefer `-Xjdk-release=<version>` over `-jvm-target` alone — it validates your code against that JDK's API surface, just like `javac --release`.

### 4.3 Kotlin/JS options

| Option | Value | Description |
|--------|-------|-------------|
| `-target` | `{es5\|es2015}` | Generate JS for the specified ECMAScript version |
| `-module-kind` | `{plain\|amd\|commonjs\|umd\|es}` | The kind of JS module generated; ES modules are the default for the `es2015` target |
| `-source-map` | — | Generate a source map |
| `-source-map-embed-sources` | `{always\|never\|inlining}` | Embed source files into the source map |
| `-libraries` | `<path>` | Paths to Kotlin libraries (`.meta.js`/`.kjsm`), path-separator separated |
| `-ir-output-dir` | `<directory>` | Destination for generated files |
| `-ir-output-name` | `<name>` | Base name of generated files |
| `-main` | `{call\|noCall}` | Whether `main` should be called on execution |

> [!NOTE]
> Kotlin/JS uses the IR backend. Many JS controls are advanced (`-X`) options: `-Xir-per-module` / `-Xir-per-file` (output granularity), `-Xir-dce` (dead-code elimination), `-Xgenerate-dts` (emit a TypeScript `.d.ts`), and `-Xes-classes`/`-Xes-arrow-functions`/`-Xes-generators` (ES2015 codegen).

### 4.4 Kotlin/Native options

The Native compiler (`konanc`, normally invoked through Gradle) produces executables, libraries, and Apple frameworks via LLVM.

| Option | Value | Description |
|--------|-------|-------------|
| `-output` / `-o` | `<name>` | Output name |
| `-produce` / `-p` | `{program\|static\|dynamic\|framework\|library\|bitcode}` | Output file kind |
| `-target` | `<target>` | Set the hardware target (see `-list-targets`) |
| `-list-targets` | — | List available hardware targets |
| `-library` / `-l` | `<path>` | Link with the given library |
| `-entry` / `-e` | `<name>` | Qualified entry-point name |
| `-g` | — | Emit debug information |
| `-opt` | — | Enable optimizations during compilation |
| `-enable-assertions` / `-ea` | — | Enable runtime assertions in generated code |
| `-generate-test-runner` / `-tr` | — | Produce a runner for unit tests |
| `-linker-options` / `-linker-option` | `<arg>` | Pass arguments to the linker |
| `-no-default-libs` | — | Don't automatically link the libraries from `dist/klib` |
| `-nomain` | — | Assume `main` is provided by an external library |

> [!TIP]
> To build an Apple framework for iOS/macOS interop, use `-produce framework -target ios_arm64`. Advanced caching options like `-Xauto-cache-from` and `-Xic-cache-dir` speed up repeated Native builds; in practice the Kotlin Gradle plugin manages these for you.

### 4.5 Kotlin/Wasm options

WebAssembly support is driven entirely through advanced options:

| Option | Description |
|--------|-------------|
| `-Xwasm` | Use the WebAssembly compiler backend |
| `-Xwasm-target` | Select the Wasm target: `wasm-js` or `wasm-wasi` |
| `-Xwasm-debug-info` | Add debug info to the compiled WebAssembly module |
| `-Xwasm-generate-wat` | Generate a `.wat` (WebAssembly text) file |
| `-Xwasm-use-traps-instead-of-exceptions` | Use traps instead of throwing exceptions |

> [!NOTE]
> Kotlin/Wasm is experimental. Build it through the Kotlin Gradle plugin's `wasmJs` or `wasmWasi` targets rather than calling the compiler directly.

---

## 5. Language Version and API Version

Two options control which language features and library declarations are available:

- `-language-version <version>` — accept the syntax and semantics of that Kotlin version. Use it to keep a codebase on an older dialect while running a newer compiler.
- `-api-version <version>` — restrict usage to declarations available in that version of the bundled libraries, so you don't accidentally depend on newer stdlib APIs.

```bash
# Compile with the 2.4 compiler but stay source-compatible with 2.2 and
# only use stdlib API present in 2.2
kotlinc app.kt -language-version 2.2 -api-version 2.2 -d app.jar
```

> [!IMPORTANT]
> `-api-version` cannot be greater than `-language-version`. If you must build the standard library itself (an unusual case), the compiler offers `-Xsuppress-api-version-greater-than-language-version-error`, but application code should never need it.

> [!TIP]
> Adopt experimental features gradually. Most experimental language features are gated behind their own `-X` flag (for example `-Xcontext-parameters`, `-Xwhen-guards`, `-Xmulti-dollar-interpolation`). Turn them on individually rather than relying on `-XXLanguage`, which is an internal escape hatch.

---

## 6. Scripting

Kotlin scripts (`.kts`) are programs that run top-to-top without a `main` function. They are useful for build logic, automation, and quick computations.

```kotlin
// listSizes.main.kts
import java.io.File

File(".").walkTopDown()
    .filter { it.isFile && it.extension == "kt" }
    .forEach { println("${it.length()}\t${it.path}") }
```

```bash
kotlinc -script listSizes.main.kts
```

> [!NOTE]
> The scripting plugin is enabled by default. You can disable default script support with `-Xdisable-default-scripting-plugin`, set a custom resolver environment with `-Xscript-resolver-environment=key=value`, or provide your own script definitions with `-script-templates`. The `.main.kts` extension activates a script template that supports `@file:DependsOn(...)` and `@file:Repository(...)` annotations for declaring dependencies inline.

> [!WARNING]
> Use `-Xallow-any-scripts-in-source-roots` only when you deliberately want scripts compiled alongside regular sources. By default, scripts in source roots are not compiled as ordinary `.kt` files.

---

## 7. Building Projects with Gradle and Maven

For anything larger than a single file, use a build tool. Both apply the Kotlin compiler with the right classpath, incremental compilation, and target wiring.

### 7.1 Gradle (recommended)

A minimal Kotlin/JVM build using the Kotlin Gradle plugin:

```kotlin
// build.gradle.kts
plugins {
    kotlin("jvm") version "2.4.0"
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("org.jetbrains.kotlin:kotlin-stdlib")
    testImplementation(kotlin("test"))
}
```

Build and test:

```bash
./gradlew build
./gradlew test
```

Configure compiler options through the plugin's DSL rather than raw flags:

```kotlin
kotlin {
    compilerOptions {
        jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
        languageVersion.set(org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_2_4)
        allWarningsAsErrors.set(true)
    }
}
```

> [!TIP]
> Multiplatform projects apply `kotlin("multiplatform")` and declare targets (`jvm()`, `js()`, `iosArm64()`, `wasmJs()`, …) in a single build script. The plugin sets up the `commonMain` source set plus per-platform source sets so you write shared code once and platform-specific code where needed.

### 7.2 Maven

The Kotlin Maven plugin compiles `src/main/kotlin` through the `kotlin-maven-plugin`:

```xml
<plugin>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-maven-plugin</artifactId>
    <version>${kotlin.version}</version>
    <executions>
        <execution>
            <id>compile</id>
            <phase>compile</phase>
            <goals><goal>compile</goal></goals>
        </execution>
    </executions>
</plugin>
```

```bash
mvn compile
mvn test
```

> [!NOTE]
> Pass compiler options through `<configuration><args>` in the plugin block (for example `<arg>-Xjsr305=strict</arg>`), and add compiler plugins through `<compilerPlugins>`. The Maven plugin and several other library artifacts are built separately with Maven in this repository (see `libraries/ReadMe.md`).

---

## 8. Multiplatform at a Glance

Kotlin compiles the same language and standard library to several targets. You usually select targets in your Gradle build; under the hood each maps to a compiler backend.

| Target | Output | Backend |
|--------|--------|---------|
| Kotlin/JVM | `.class` files / JAR; runs on any JVM | JVM IR backend |
| Kotlin/JS | JavaScript modules (`plain`, `commonjs`, `umd`, `amd`, `es`) | JS IR backend |
| Kotlin/Native | Native executables, static/dynamic libraries, Apple frameworks | LLVM-based Native backend |
| Kotlin/Wasm | WebAssembly (`wasm-js` for browsers, `wasm-wasi` for WASI hosts) | Wasm backend |
| Metadata (`common`) | `.klib` of common declarations consumed by platform compilations | Metadata compiler |

Shared code lives in a common source set and uses `expect`/`actual` declarations to bind to platform-specific implementations:

```kotlin
// commonMain
expect fun platformName(): String

// jvmMain
actual fun platformName(): String = "JVM"

// nativeMain
actual fun platformName(): String = "Native"
```

> [!NOTE]
> Compiling common code requires multiplatform support. The Gradle plugin enables it automatically; at the raw-compiler level it is `-Xmulti-platform`. Cross-platform libraries are distributed as `.klib` files and passed with `-Xklib` (JVM) or `-library`/`-l` (Native).

---

## 9. The Standard Library

Every Kotlin program links against `kotlin-stdlib`, which provides the core types and thousands of functions. Highlights you will use constantly:

- **Collections** — `List`, `Set`, `Map`, and a rich set of operators: `map`, `filter`, `fold`, `groupBy`, `associateBy`, `sortedBy`, `windowed`, `chunked`.
- **Sequences** — lazy pipelines via `asSequence()` for large or infinite data.
- **Scope functions** — `let`, `run`, `with`, `apply`, `also` for concise object configuration and null handling.
- **Null safety helpers** — `?.`, `?:`, `requireNotNull`, `checkNotNull`, `takeIf`, `takeUnless`.
- **Text** — `String` extensions like `trimIndent`, `split`, `substringBefore`, `lines`, and multi-dollar string interpolation (experimental, `-Xmulti-dollar-interpolation`).
- **Result and contracts** — `Result<T>`, `runCatching`, and `kotlin.contracts` for smarter compiler analysis.

```kotlin
val byFirstLetter = listOf("apple", "apricot", "banana", "cherry")
    .groupBy { it.first() }
// {a=[apple, apricot], b=[banana], c=[cherry]}
```

> [!TIP]
> The stdlib ships platform-tailored variants — `jvm`, `js`, `native-wasm`, `wasm`, plus `jdk7`/`jdk8` add-ons that expose newer JDK APIs (such as `java.time` and `java.nio.file` helpers). On the JVM, `-no-stdlib` removes it from the classpath; you almost never want that outside of building the stdlib itself.

> [!NOTE]
> `kotlin.test` provides a multiplatform assertion API (`assertEquals`, `assertTrue`, `assertFailsWith`) that delegates to the underlying framework (JUnit on JVM, Mocha on JS, and so on). Add it with `testImplementation(kotlin("test"))`.

---

## 10. Compiler Plugins

The Kotlin distribution bundles compiler plugins that generate or transform code at compile time. Enable them through your build tool (each has a Gradle plugin id) or with `-Xplugin`/`-P` on the command line.

| Plugin | What it does |
|--------|--------------|
| `kotlinx-serialization` | Generate serializers for `@Serializable` classes |
| `kapt` | Run Java annotation processors against Kotlin code |
| `allopen` | Make classes with marked annotations `open` (for Spring, mocking) |
| `noarg` | Synthesize a no-arg constructor for marked classes (JPA entities) |
| `sam-with-receiver` | Treat the first parameter of a SAM interface as a receiver |
| `parcelize` | Generate `Parcelable` implementations on Android |
| `lombok` | Interoperate with Lombok-generated Java members |
| `power-assert` | Produce detailed assertion failure messages |
| `atomicfu` | Compile `kotlinx.atomicfu` atomics efficiently |
| `compose` | The Jetpack/JetBrains Compose compiler plugin |
| `assign-plugin` | Allow operator-style assignment for specific types (Gradle DSLs) |
| `jvm-abi-gen` | Generate ABI-only JARs to speed up incremental builds |
| `js-plain-objects` | Generate plain JS objects from Kotlin interfaces |
| `kotlin-dataframe` | Compile-time support for the DataFrame library |

Example — applying serialization in Gradle:

```kotlin
plugins {
    kotlin("jvm") version "2.4.0"
    kotlin("plugin.serialization") version "2.4.0"
}
```

```kotlin
import kotlinx.serialization.*
import kotlinx.serialization.json.Json

@Serializable
data class Point(val x: Int, val y: Int)

fun main() {
    val json = Json.encodeToString(Point(1, 2))
    println(json)                       // {"x":1,"y":2}
    println(Json.decodeFromString<Point>(json))
}
```

> [!NOTE]
> `allopen`, `noarg`, and `sam-with-receiver` ship preconfigured presets — `kotlin("plugin.spring")`, `kotlin("plugin.jpa")` — that apply the plugin with the right marker annotations for those frameworks.

> [!TIP]
> To pass an option to a plugin from the command line, use `-P plugin:<pluginId>:<optionName>=<value>` and load the plugin jar with `-Xplugin=<path>`. Build tools translate their DSL into exactly these flags.

---

## 11. Troubleshooting

### Error: `no kotlin.home system property was passed`

**Cause:** The `kotlin` runner was started without the distribution location. **Solution:** Use the `kotlin` launcher script (which sets `-Dkotlin.home`) rather than invoking the runner JAR directly, or pass `-Dkotlin.home=<path-to-kotlinc>`. **Prevention:** Keep `kotlinc/bin` on your `PATH` and call `kotlin`/`kotlinc`, not the jars.

### Error: `error: unable to find main(...)` / wrong class name when running

**Cause:** A top-level `main` in `foo.kt` compiles to `FooKt`, not `Foo` or `Main`. **Solution:** Run `kotlin -cp out/ FooKt` (file name capitalized + `Kt`). **Prevention:** Build a JAR with `-include-runtime -d app.jar` and run `java -jar app.jar`; the manifest records the correct entry point.

### Error: `cannot access built-in declaration` with `-no-stdlib`

**Cause:** You removed the stdlib from the classpath. **Solution:** Drop `-no-stdlib`, or, when you genuinely build without it, add `-Xsuppress-missing-builtins-error`. **Prevention:** Let the build tool manage the stdlib dependency.

### Error: `Inconsistent JVM-target compatibility detected`

**Cause:** Kotlin's `-jvm-target` and Java's compile target differ in a mixed module. **Solution:** Set both to the same value — `-jvm-target 17` and `--release 17` (or the Gradle `jvmTarget`/`sourceCompatibility` equivalents). **Prevention:** Configure one JVM toolchain in Gradle and let it drive both compilers.

### Warning: `language version X is deprecated`

**Cause:** You pinned `-language-version` to a version the current compiler is phasing out. **Solution:** Move to a supported version, or temporarily quiet it with `-Xsuppress-version-warnings`. **Prevention:** Track the language version forward as you upgrade the compiler.

### Build fails: `Dependency verification failed` (building Kotlin from source)

**Cause:** The repository enables Gradle dependency verification; a local artifact is missing or has a different hash than `gradle/verification-metadata.xml`. **Solution:** Re-resolve and regenerate metadata with `./gradlew --write-verification-metadata sha256 -Pkotlin.native.enabled=true resolveDependencies` (or run `./scripts/update-verification-metadata.sh`). **Prevention:** Only update `verification-metadata.xml` in commits that change the build.

### Windows: `Filename too long` during a source checkout or build

**Cause:** Deeply nested test-data paths exceed Windows' default path limit. **Solution:** Enable long paths for the repo: `git config core.longpaths true`. **Prevention:** Clone with long paths enabled from the start.

### First Native or `idea-full` build times out

**Cause:** Kotlin/Native and IDE dependencies (`intellij-core`, `idea-full`) are large downloads. **Solution:** Increase timeouts: `./gradlew -Dhttp.socketTimeout=60000 -Dhttp.connectionTimeout=60000 <task>`. **Prevention:** Run the first build on a fast connection; subsequent builds reuse the cache.

---

## 12. FAQ

**Q: What is the difference between `kotlinc` and `kotlinc-jvm`?**
`kotlinc` is an alias for `kotlinc-jvm`. Use `kotlinc-js` to target JavaScript. Kotlin/Native and Kotlin/Wasm are normally built through Gradle.

**Q: Do I need a JDK to use Kotlin?**
Yes for Kotlin/JVM — `kotlinc` runs on the JVM and produces bytecode that runs on a JDK/JRE. Kotlin/Native produces standalone binaries that don't require a JVM at runtime, but you still build them with the toolchain.

**Q: How do I pick the bytecode version?**
Use `-jvm-target <version>` (`1.8` and `9`–`26`, default `1.8`). To also validate against that JDK's API surface, prefer `-Xjdk-release=<version>`.

**Q: What language version does this compiler default to?**
The default language version on this branch is `2.4`. Override it with `-language-version` to stay source-compatible with an older dialect.

**Q: How do I enable an experimental feature?**
Turn on its specific `-X` flag (for example `-Xcontext-parameters`). Avoid `-XXLanguage`, which is an internal escape hatch not meant for production.

**Q: How do I make a runnable JAR?**
`kotlinc src/ -include-runtime -d app.jar`, then `java -jar app.jar`. The `-include-runtime` flag bundles the stdlib.

**Q: How do I run a `.kts` script?**
`kotlinc -script myScript.kts`. For dependency-aware scripts, use the `.main.kts` extension and `@file:DependsOn(...)` annotations.

**Q: What's the difference between standard and `-X` options?**
Standard options (shown by `-help`) are stable. `-X` options (shown by `-X`) are advanced and may change between releases. `-XX` options are internal and unsupported.

**Q: Should I call `kotlinc` directly in a real project?**
No — use Gradle or Maven. They handle dependency resolution, incremental compilation, multiplatform targets, and plugin wiring. The CLI is best for scripts, experiments, and learning.

**Q: How do I add Kotlin serialization, Spring openness, or JPA no-arg constructors?**
Apply the matching Gradle plugin: `kotlin("plugin.serialization")`, `kotlin("plugin.spring")`, or `kotlin("plugin.jpa")`. See Section 10.

**Q: How do I share code across platforms?**
Apply `kotlin("multiplatform")`, declare your targets, write shared code in `commonMain`, and bind platform specifics with `expect`/`actual`.

**Q: Where do I report bugs or request features?**
Kotlin is tracked in YouTrack under the `KT` project (`youtrack.jetbrains.com/issues/KT`). The repository's `ChangeLog.md` lists issues fixed per release.

**Q: What license is Kotlin under?**
Apache License 2.0.

---

## 13. Command Reference

| Task | Command |
|------|---------|
| Compile to a JAR with runtime | `kotlinc src/ -include-runtime -d app.jar` |
| Compile to a directory | `kotlinc src/ -d out/` |
| Run a compiled class | `kotlin -cp out/ MainKt` |
| Run a JAR | `java -jar app.jar` |
| Evaluate an expression | `kotlinc -e "println(40 + 2)"` |
| Run a script | `kotlinc -script file.kts` |
| Open the REPL | `kotlinc` (no source files) |
| Print version | `kotlinc -version` |
| List standard options | `kotlinc -help` |
| List advanced options | `kotlinc -X` |
| Set bytecode target | `kotlinc app.kt -jvm-target 17 -d app.jar` |
| Pin the language version | `kotlinc app.kt -language-version 2.2` |
| Treat warnings as errors | `kotlinc app.kt -Werror` |
| Compile to JavaScript | `kotlinc-js app.kt -ir-output-dir out -ir-output-name app` |
| Build a project (Gradle) | `./gradlew build` |
| Build a project (Maven) | `mvn compile` |

| Resource | Location |
|----------|----------|
| Official site | `https://kotlinlang.org/` |
| Try Kotlin online | `https://play.kotlinlang.org/` |
| Standard library API | `https://kotlinlang.org/api/latest/jvm/stdlib/index.html` |
| Issue tracker | `https://youtrack.jetbrains.com/issues/KT` |
| Source repository | `https://github.com/JetBrains/kotlin` |

---

_Generated June 2026 from JetBrains/kotlin at 2a37504. AI-generated documentation. The library is checked by sampling (three repositories so far); this guide was not individually reviewed. Verify against the project before relying on it. Unofficial; not affiliated with or reviewed by the project._
