Kotlin compiler versions and experimental features

suggest change

Every Kotlin release adds language features, but not all of them are on by default. A new feature usually ships first as experimental behind a compiler flag, gets feedback for a release or two, and then becomes stable: on by default, no flag needed.

This article explains how to control which version of the language you compile against and how to turn previews on:

All examples were compiled with Kotlin 2.4.21 (kotlinc) and Gradle 9.8.1 on JDK 25. See Compile and Run Kotlin Code in Command Line for kotlinc basics and Gradle configuration for setting up a Gradle project.

How Kotlin versions work

Kotlin version numbers look like 2.4.21:

Check which compiler you have with kotlinc -version:

info: kotlinc-jvm 2.4.21 (JRE 25.0.4.1+1-LTS)

At runtime, KotlinVersion.CURRENT gives the version of the standard library your program runs with:

fun main() {
    println("Kotlin ${KotlinVersion.CURRENT}")
    println(KotlinVersion.CURRENT.isAtLeast(2, 2))
    println(KotlinVersion.CURRENT >= KotlinVersion(2, 0, 0))
}

Output:

Kotlin 2.4.21
true
true

The K2 compiler

Kotlin 2.0 replaced the compiler front-end (the part that parses, resolves names and checks types) with a new one called K2. It compiles faster, gives one shared front-end for JVM, JS, Wasm and Native, and has a much better data-flow analysis. You can see the effect in smart casts: K2 smart casts through local Boolean variables, || checks and inline lambdas, where the old K1 compiler gave up. Smart casts with the K2 compiler covers this in detail.

Most features added since 2.0 (guard conditions, context parameters, non-local break/continue, multi-dollar interpolation, explicit backing fields) exist only in K2.

In Kotlin 2.4 K2 is the only front-end. The oldest language version it accepts is 2.0, so there's no way to switch back to K1:

$ kotlinc -language-version 1.9 ver.kt -d out
error: language version 1.9 is no longer supported; use version 2.0 or greater instead.

-language-version: which language features are allowed

-language-version makes the compiler behave like an older (or newer) version of Kotlin. Features added after that version are rejected. The full list of accepted values is in the error for an unknown version:

$ kotlinc -language-version 3.0 ver.kt -d out
error: unknown language version: 3.0
Supported language versions: 2.0 (deprecated), 2.1 (deprecated), 2.2, 2.3, 2.4, 2.5 (experimental), 2.6 (experimental)

So Kotlin 2.4.21 supports:

Here is a file that uses two features that became stable in Kotlin 2.2: a guard condition in when and multi-dollar string interpolation:

sealed interface Shape
data class Circle(val r: Double) : Shape
data class Square(val side: Double) : Shape

fun describe(s: Shape) = when (s) {
    is Circle if s.r == 0.0 -> "a point"
    is Circle -> "circle r=${s.r}"
    is Square -> "square ${s.side}"
}

fun main() {
    val schema = $$"""{"$schema": "x", "name": "$${describe(Circle(0.0))}"}"""
    println(schema)
}

It compiles with -language-version 2.2 but not with 2.1:

$ kotlinc -language-version 2.1 guards.kt -d out
warning: language version 2.1 is deprecated and its support will be removed in a future version of Kotlin. Update the version to 2.2.
guards.kt:6:15: error: the feature "when guards" is only available since language version 2.2
    is Circle if s.r == 0.0 -> "a point"
              ^^^^^^^^^^^^^
guards.kt:12:18: error: the feature "multi dollar interpolation" is only available since language version 2.2
    val schema = $$"""{"$schema": "x", "name": "$${describe(Circle(0.0))}"}"""
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Output with the default language version:

{"$schema": "x", "name": "a point"}

See Guard conditions in when and Multi-dollar string interpolation for the features themselves.

When would you lower the language version? Mostly in libraries and shared code: if your code must also be compiled by teammates or consumers on an older Kotlin, setting -language-version to that version makes the newer compiler reject anything they can't handle. Applications usually leave it at the default.

-api-version: which standard library APIs are allowed

-api-version does the same for the standard library: declarations added (or made stable) after that version are treated as unavailable or experimental. It can't be higher than the language version.

kotlin.time.Instant and Clock became stable in the 2.3 standard library, and the core kotlin.uuid.Uuid API in 2.4:

import kotlin.time.Clock
import kotlin.uuid.Uuid

fun main() {
    println(Clock.System.now() > kotlin.time.Instant.fromEpochSeconds(0))
    println(Uuid.random().toString().length)
    println(listOf(3, 1, 2).sorted())
}

With -api-version 2.4 (the default) this compiles with no opt-in. With 2.3 only Uuid needs one:

$ kotlinc -api-version 2.3 api.kt -d out
api.kt:6:13: error: this declaration needs opt-in. Its usage must be marked with '@kotlin.uuid.ExperimentalUuidApi' or '@OptIn(kotlin.uuid.ExperimentalUuidApi::class)'
    println(Uuid.random().toString().length)
            ^^^^
api.kt:6:18: error: this declaration needs opt-in. Its usage must be marked with '@kotlin.uuid.ExperimentalUuidApi' or '@OptIn(kotlin.uuid.ExperimentalUuidApi::class)'
    println(Uuid.random().toString().length)
                 ^^^^^^

With -api-version 2.2 the Clock and Instant calls fail the same way with @kotlin.time.ExperimentalTime. And the API version must not exceed the language version:

$ kotlinc -language-version 2.2 -api-version 2.3 api.kt -d out
error: -api-version (2.3) cannot be greater than -language-version (2.2).

Use -api-version when your code runs against an older kotlin-stdlib than the compiler (for example a Gradle plugin that runs inside Gradle's bundled Kotlin). See UUIDs for the Uuid API.

Experimental language features and -X flags

An experimental language feature is off by default. If you use it anyway, the error tells you which flag turns it on:

fun main() {
    val list: List<Int> = [1, 2, 3]
    val set: Set<String> = ["a", "b", "a"]
    val mutable: MutableList<String> = []
    mutable += "x"
    println(list)
    println(set)
    println(mutable)
}
$ kotlinc coll.kt -d out
coll.kt:2:27: error: the feature "collection literals" is experimental and should be enabled explicitly. This can be done by supplying the compiler argument '-Xcollection-literals', but note that no stability guarantees are provided.
    val list: List<Int> = [1, 2, 3]
                          ^^^^^^^^^

With the flag:

$ kotlinc -Xcollection-literals coll.kt -d out
$ kotlin -cp out CollKt
[1, 2, 3]
[a, b]
[x]

Options that start with -X are "advanced" options. kotlinc -X lists all of them. They have no compatibility guarantees: an -X flag can change meaning or disappear in the next release, and code that compiles with it today may not compile tomorrow.

There are three ways to turn on a feature that isn't stable yet:

  1. A dedicated -X flag, like -Xcollection-literals or -Xcontext-sensitive-resolution. This is what the error message suggests and what you should normally use.
  2. -XXLanguage:+FeatureName turns on any language feature by its internal name, even ones without their own flag. -XXLanguage:-FeatureName turns a feature off. These are internal options, and the compiler warns loudly about them (example below).
  3. A newer, experimental -language-version such as 2.5. It turns on features already scheduled for that version, together with everything else that changes in it. In 2.4.21, -language-version 2.5 enables explicit context arguments and the full name-based destructuring syntax without separate flags, but not collection literals.

Some errors say which of these applies. For a feature planned for the next version you get:

eca.kt:10:15: error: the feature "explicit context arguments" is only available since language version 2.5

-XXLanguage for features without a flag

Unnamed local variables (val _ = f()) have no -X flag in Kotlin 2.4:

fun save(s: String): Boolean { println("saved $s"); return true }

fun main() {
    val _ = save("a")
    val _ = save("b")
}
$ kotlinc un.kt -d out
un.kt:4:9: error: the feature "unnamed local variables" is experimental and should be enabled explicitly. This can be done by supplying the compiler argument '-XXLanguage:+UnnamedLocalVariables', but note that no stability guarantees are provided.
    val _ = save("a")
        ^

With the flag it compiles, after a warning that you're using unsupported options:

$ kotlinc -XXLanguage:+UnnamedLocalVariables un.kt -d out
warning: ATTENTION!
This build uses unsafe internal compiler arguments:

-XXLanguage:+UnnamedLocalVariables

This mode is not recommended for production use,
as no stability/compatibility guarantees are given on
compiler or generated code. Use it at your own risk!

$ kotlin -cp out UnKt
saved a
saved b

The minus form disables a feature, even a stable one. That's occasionally useful for checking that code doesn't depend on something:

$ kotlinc -XXLanguage:-WhenGuards guards.kt -d out
...
guards.kt:6:15: error: the feature "when guards" is disabled
    is Circle if s.r == 0.0 -> "a point"
              ^^^^^^^^^^^^^

When a feature becomes stable: redundant flags

The flag for a feature doesn't go away the moment the feature becomes stable. It just stops doing anything, and the compiler says so. These features were experimental in 2.1-2.3 and are stable in 2.4:

$ kotlinc -Xcontext-parameters -Xnon-local-break-continue -Xmulti-dollar-interpolation -Xexplicit-backing-fields -Xnested-type-aliases -Xdata-flow-based-exhaustiveness ver.kt -d out
warning: the argument '-Xcontext-parameters' is redundant for the current language version 2.4.
warning: the argument '-Xnon-local-break-continue' is redundant for the current language version 2.4.
warning: the argument '-Xmulti-dollar-interpolation' is redundant for the current language version 2.4.
warning: the argument '-Xexplicit-backing-fields' is redundant for the current language version 2.4.
warning: the argument '-Xnested-type-aliases' is redundant for the current language version 2.4.
warning: the argument '-Xdata-flow-based-exhaustiveness' is redundant for the current language version 2.4.

When you upgrade Kotlin, look for these warnings in your build output and delete the flags. They aren't harmless: with -Werror (see below) they break the build.

The flag isn't redundant with an older language version. -language-version 2.2 -Xexplicit-backing-fields compiles quietly and turns the feature on for 2.2 code.

A feature that was replaced rather than stabilized turns its old flag into an error. Context receivers were superseded by context parameters:

$ kotlinc -Xcontext-receivers ver.kt -d out
error: experimental context receivers are superseded by context parameters.
Remove the '-Xcontext-receivers' compiler argument and migrate to the new syntax.

See the context parameters proposal for more details: https://kotl.in/context-parameters

Experimental features in Kotlin 2.4

These are the language previews you can try in Kotlin 2.4.21. Each needs the flag shown; without it, the code doesn't compile.

Collection literals: -Xcollection-literals

Square brackets build a collection of the expected type. Without an expected type you get a List (an ArrayList on the JVM), and arrays work too:

fun main() {
    val xs = [1, 2, 3]
    println(xs::class.simpleName + " " + xs)
    val arr: IntArray = [4, 5]
    println(arr.sum())
}

Output with -Xcollection-literals:

ArrayList [1, 2, 3]
9

Context-sensitive resolution: -Xcontext-sensitive-resolution

When the expected type is an enum or a sealed type, you can leave out the type name in front of its entries:

enum class Color { RED, GREEN, BLUE }

fun hex(c: Color): String = when (c) {
    RED -> "#f00"
    GREEN -> "#0f0"
    BLUE -> "#00f"
}

fun isWarm(c: Color) = c == RED

fun main() {
    println(hex(GREEN))
    println(isWarm(Color.RED))
}

Output with the flag:

#0f0
true

Without it, RED is an unresolved reference. Sealed classes and interfaces shows this with sealed hierarchies.

Unused return value checker: -Xreturn-value-checker

The checker warns when you call a function for its result and then drop the result. check only reports; full also lets the compiler mark your own declarations automatically. The standard library is already annotated, and @file:MustUseReturnValues extends the check to your own functions (here the generated copy()):

@file:MustUseReturnValues

data class User(val name: String, val age: Int)

fun birthday(u: User): User {
    u.copy(age = u.age + 1)   // result ignored: bug
    return u
}

@IgnorableReturnValue
fun log(msg: String): Boolean { println(msg); return true }

fun main() {
    val names = listOf("a")
    names + "b"                // result ignored: bug
    " hi ".trim()              // result ignored: bug
    log("ok")                  // fine, marked ignorable
    println(birthday(User("Ann", 30)))
}
$ kotlinc -Xreturn-value-checker=check rv.kt -d out
rv.kt:6:7: warning: unused return value of 'copy'.
    u.copy(age = u.age + 1)   // result ignored: bug
      ^^^^
rv.kt:15:11: warning: unused return value of 'plus'.
    names + "b"                // result ignored: bug
          ^
rv.kt:16:12: warning: unused return value of 'trim'.
    " hi ".trim()              // result ignored: bug
           ^^^^

Without the flag, the annotations themselves are an error:

rv.kt:1:1: error: ignorability-related annotations are experimental and cannot be used with -Xreturn-value-checker in disabled state.

Explicit context arguments: -Xexplicit-context-arguments

Normally a function with context parameters takes its context from the scope. This preview lets you also pass it by name, like a regular argument:

class Logger(val prefix: String) {
    fun log(msg: String) = println("$prefix $msg")
}

context(logger: Logger)
fun work(task: String) = logger.log("doing $task")

fun main() {
    with(Logger("[implicit]")) { work("a") }
    work("b", logger = Logger("[explicit]"))
}

Output with -Xexplicit-context-arguments (or -language-version 2.5):

[implicit] doing a
[explicit] doing b

Local type aliases: -Xlocal-type-aliases

typealias inside a function body:

fun main() {
    typealias Pairs = List<Pair<String, Int>>
    val p: Pairs = listOf("a" to 1, "b" to 2)
    println(p.sumOf { it.second })
}

Output with the flag:

3

Type aliases nested in classes are already stable in 2.4.

Companion blocks: -Xcompanion-blocks-and-extensions

A companion { } block without the object keyword declares members you call on the class name:

class Point(val x: Int, val y: Int) {
    companion {
        fun origin() = Point(0, 0)
    }
}

fun main() {
    println(Point.origin().x)
}

Output with the flag:

0

Name-based destructuring: -Xname-based-destructuring

-Xname-based-destructuring=only-syntax|name-mismatch|complete makes (val end, val start) = range match properties by name instead of position. Destructuring explains the modes and how to prepare existing code.

Status table

What a Kotlin 2.4.21 compiler does with recent features:

Feature Introduced Status in 2.4 How to enable
K2 compiler, smarter smart casts 2.0 stable on
Guard conditions in when 2.1 preview stable since 2.2 on
Non-local break/continue 2.1 preview stable since 2.2 on
Multi-dollar interpolation $$"..." 2.1 preview stable since 2.2 on
Context parameters 2.2 preview stable on (old -Xcontext-receivers is an error)
Nested type aliases 2.2 beta stable on
@all: annotation target 2.2 stable on
Data-flow when exhaustiveness 2.2.20 stable on
Explicit backing fields 2.3 experimental stable on
Context-sensitive resolution 2.2 experimental -Xcontext-sensitive-resolution
Unnamed local variables val _ 2.2.20 experimental -XXLanguage:+UnnamedLocalVariables
Unused return value checker 2.3 experimental -Xreturn-value-checker=check
Collection literals 2.4 experimental -Xcollection-literals
Name-based destructuring 2.4 experimental -Xname-based-destructuring=...
Explicit context arguments 2.4 experimental -Xexplicit-context-arguments or -language-version 2.5
Local type aliases 2.4 experimental -Xlocal-type-aliases
Companion blocks 2.4 experimental -Xcompanion-blocks-and-extensions

Properties and explicit backing fields, Non-local break and continue and Value classes cover some of the stable ones.

Experimental library APIs work differently. They don't need compiler flags; you opt in with @OptIn(...) in code or -opt-in=<marker> for a whole module. For example Uuid.generateV7() needs kotlin.uuid.ExperimentalUuidApi and common atomics need kotlin.concurrent.atomics.ExperimentalAtomicApi. See Opt-in requirements.

Controlling warnings

Take this file:

fun greet(name: String, unused: Int): String {
    val x = 42
    val s: String = name
    return s!! + "!"
}

fun main() {
    println(greet("Kotlin", 1))
}

By default K2 reports only one warning:

warn.kt:4:13: warning: unnecessary non-null assertion (!!) on a non-null receiver of type 'String'.
    return s!! + "!"
            ^^

-Wextra: more checks

-Wextra turns on additional K2 checkers, such as unused variables. -Xrender-internal-diagnostic-names prints the internal name of each diagnostic, which you need for -Xwarning-level:

$ kotlinc -Wextra -Xrender-internal-diagnostic-names warn.kt -d out
warn.kt:2:9: warning: [UNUSED_VARIABLE] Variable is unused.
    val x = 42
        ^
warn.kt:4:13: warning: [UNNECESSARY_NOT_NULL_ASSERTION] Unnecessary non-null assertion (!!) on a non-null receiver of type 'String'.
    return s!! + "!"
            ^^

-Werror and -nowarn

-Werror fails the compilation (exit code 1) if there is any warning:

$ kotlinc -Werror warn.kt -d out
error: warnings found and -Werror specified
warn.kt:4:13: warning: unnecessary non-null assertion (!!) on a non-null receiver of type 'String'.
    return s!! + "!"
            ^^

-nowarn hides all warnings.

-Xwarning-level: per-warning severity

-Xwarning-level=NAME:error|warning|disabled changes the severity of one diagnostic:

$ kotlinc -Xwarning-level=UNNECESSARY_NOT_NULL_ASSERTION:error warn.kt -d out
warn.kt:4:13: error: unnecessary non-null assertion (!!) on a non-null receiver of type 'String'.
    return s!! + "!"
            ^^

$ kotlinc -Werror -Xwarning-level=UNNECESSARY_NOT_NULL_ASSERTION:warning warn.kt -d out
warn.kt:4:13: warning: unnecessary non-null assertion (!!) on a non-null receiver of type 'String'.
    return s!! + "!"
            ^^

The second command succeeds (exit code 0). A typo in the name is an error: warning with name "NOPE" does not exist. The older -Xsuppress-warning=NAME still works but is deprecated in favor of -Xwarning-level=NAME:disabled.

-progressive

When the Kotlin team fixes a compiler bug that made some incorrect code compile, or deprecates a language construct, existing code gets a migration period: first a warning, an error in a later version. -progressive makes such fixes and deprecations take effect immediately. Code that compiles in progressive mode also compiles without it, so it's a safe setting for projects that always use the latest compiler.

It only makes sense with the latest language version:

$ kotlinc -progressive -language-version 2.2 warn.kt -d out
warning: '-progressive' is meaningful only for the latest language version (2.4), while this build uses 2.2
Compiler behavior in such mode is undefined; consider moving to the latest stable version or turning off progressive mode.

The deprecation warnings for old language and API versions can be silenced with -Xsuppress-version-warnings.

JVM bytecode and JDK API level

Two more flags affect what the compiler produces on the JVM:

fun main() {
    val t = Thread.ofVirtual().start { println("virtual: ${Thread.currentThread().isVirtual}") }
    t.join()
}

Virtual threads are a JDK 21 API. With -jvm-target 17 this compiles (and fails at runtime on a JDK 17). With -Xjdk-release=17 the compiler catches it:

$ kotlinc -Xjdk-release=17 jdk.kt -d out
jdk.kt:2:20: error: unresolved reference 'ofVirtual'.
    val t = Thread.ofVirtual().start { println("virtual: ${Thread.currentThread().isVirtual}") }
                   ^^^^^^^^^

With -Xjdk-release=21 it compiles to class file version 65 and prints virtual: true.

Compiler options in Gradle

In a Gradle build, set the same options in kotlin { compilerOptions { } }. Common options have typed properties; everything else goes in freeCompilerArgs:

// build.gradle.kts
import org.jetbrains.kotlin.gradle.dsl.KotlinVersion

plugins {
    kotlin("jvm") version "2.4.21"
    application
}

repositories {
    mavenCentral()
}

kotlin {
    jvmToolchain(25)

    compilerOptions {
        languageVersion = KotlinVersion.KOTLIN_2_4   // -language-version
        apiVersion = KotlinVersion.KOTLIN_2_4        // -api-version

        progressiveMode = true                       // -progressive
        allWarningsAsErrors = true                   // -Werror
        extraWarnings = true                         // -Wextra

        optIn.add("kotlin.uuid.ExperimentalUuidApi") // -opt-in=...

        freeCompilerArgs.addAll(
            "-Xcollection-literals",
            "-Xcontext-sensitive-resolution",
            "-Xwarning-level=UNUSED_VARIABLE:warning",
        )
    }
}

application {
    mainClass = "MainKt"
}

jvmToolchain(25) picks the JDK to compile with and sets jvmTarget to match. To target an older JVM without installing that JDK, set jvmTarget = JvmTarget.JVM_17 in compilerOptions (and the matching targetCompatibility for Java sources).

src/main/kotlin/Main.kt uses both experimental features and the opted-in API:

import kotlin.uuid.Uuid

enum class Level { LOW, HIGH }

fun label(l: Level) = when (l) {
    LOW -> "low"
    HIGH -> "high"
}

fun main() {
    val levels: List<Level> = [Level.LOW, Level.HIGH]
    val unused = 1
    println(levels.map(::label))
    println(Uuid.generateV7().toString().length)
    println("Kotlin ${KotlinVersion.CURRENT}")
}

gradle run prints the unused-variable warning (kept a warning by -Xwarning-level despite allWarningsAsErrors) and runs the program:

> Task :compileKotlin
w: file:///.../src/main/kotlin/Main.kt:12:9 Variable is unused.

> Task :run
[low, high]
36
Kotlin 2.4.21

Remove the -Xwarning-level line and the same warning fails the build:

e: warnings found and -Werror specified
e: file:///.../src/main/kotlin/Main.kt:12:9 Variable is unused.

> Task :compileKotlin FAILED

Options in kotlin { compilerOptions { } } apply to every source set, including tests. Keep experimental flags in one place, so that removing them after an upgrade is a one-line change.

Long flag lists in a file

kotlinc reads arguments from a file prefixed with @, one per line:

-Xcollection-literals
-Xcontext-sensitive-resolution
-Werror
-d
out
$ kotlinc @flags.txt coll.kt csr.kt
$ kotlin -cp out CollKt
[1, 2, 3]
[a, b]
[x]

Best practices

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents