Skip to content
Tutorials Center
My learning

Topics

Lesson 115 of 134 ยท Testing and Tooling

Opt-In, Experimental APIs and Compiler Flags

Understand Kotlin opt-in: use @OptIn and @RequiresOptIn, mark your own unstable APIs, and configure compiler flags, language and API versions and the K2 compiler.

Every language has features that are new, unfinished or easy to misuse. Kotlin's approach is not to hide them but to make you say, in code, that you know what you are doing. Libraries mark such APIs with a special annotation, and the compiler refuses to build your code until you either opt in or pass the requirement on to your own callers. The same system lets you protect the unstable parts of your own libraries.

The second half of this lesson is about the compiler itself: the -X flags you see in Gradle files, what -language-version and -api-version do, and what the K2 compiler is. This is the kind of knowledge that stops a build error from feeling like magic. It follows Gradle basics and project structure, and it uses annotations, so skim those first if the syntax is unfamiliar.

What opt-in is

An API is opt-in when its declaration carries a marker annotation that is itself annotated with @RequiresOptIn. Whoever uses the API in code must do one of two things:

  1. Propagate the requirement: mark the using declaration with the same marker. Now the requirement belongs to your callers.
  2. Opt in: mark the using declaration or file with @OptIn(Marker::class). You take responsibility, and callers are not affected.
flowchart LR
    A["Library declares<br/>@ExperimentalPricing fun dynamicPrice()"] --> B{"Your code calls it"}
    B -->|"propagate"| C["Mark your function with<br/>@ExperimentalPricing"]
    B -->|"opt in"| D["Mark your function with<br/>@OptIn(ExperimentalPricing::class)"]
    C --> E["Your callers must decide too"]
    D --> F["Callers see a normal API"]

Opt-in puts the decision in the code: propagate the warning upward, or accept it where you use the API.

Defining your own marker

Writing a marker takes four lines. The level decides how strict the compiler is: WARNING lets the code build with a warning, ERROR stops the build.

Kotlin An opt-in marker and the error it causes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

checkoutTotal opts in, so it compiles cleanly, and main can call it as if nothing special happened. Now change level to ERROR and remove the @OptIn line from checkoutTotal. You will see how the compiler reacts when a requirement is ignored. With the level set to ERROR, that mistake is a hard error, for example:

TEXT
main.kt:10:13: error: this API is experimental and may change.
    println(dynamicPrice(10))
            ^^^^^^^^^^^^

The @Retention(BINARY) line keeps the marker in the compiled class files (so users of a compiled library are checked too) while keeping it invisible to reflection. Most libraries use BINARY retention for opt-in markers.

Use ERROR when misuse can cause real harm, such as data loss or a security hole, and WARNING when the API is only likely to change. A warning that everyone suppresses teaches nobody anything, so prefer the stricter level for anything that must not be used lightly.

Propagating instead of opting in

If your function is itself part of an experimental area, mark it with the same marker. The requirement then moves one step outward:

Kotlin Propagating a marker through your own API

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The line between the two choices is a design decision. Propagate when the unstable part is visible in your own public API (a parameter or return type uses it). Opt in when it is an implementation detail, and you are willing to update the code if the API changes.

Where you can write @OptIn

@OptIn can sit on a function, class, property, local variable, expression or whole file. The narrower the scope, the less code is covered by your promise:

Kotlin
@file:OptIn(ExperimentalStdlibApi::class)   // covers the whole file

package demo

@OptIn(ExperimentalUnsignedTypes::class)    // covers one function
fun sizes() = ubyteArrayOf(1u, 2u).size

fun main() {
    @OptIn(ExperimentalStdlibApi::class)     // covers one statement
    println((0..<3).toList())
}

Prefer the smallest scope that works. A file-level opt-in is convenient but silently covers code added to the file later.

Opt-in for subclassing and implementing

Some APIs are safe to call but not safe to implement. @SubclassOptInRequired lets a library say "you may use this class freely, but extending it requires opt-in", which is useful for interfaces that might gain new methods:

Kotlin Opt-in required to subclass

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Leave out the @OptIn and the compiler reports: this class or interface requires opt-in to be implemented. Its usage must be marked with '@ExtensionPoint' or '@OptIn(ExtensionPoint::class)'.

Opt-in markers you will meet in the standard library

Marker Where it appears
ExperimentalStdlibApi Newer standard library functions not yet declared stable
ExperimentalUnsignedTypes Unsigned arrays such as UByteArray
ExperimentalContracts Declaring contracts
DelicateCoroutinesApi Dangerous coroutine APIs such as GlobalScope (see structured concurrency)
ExperimentalCoroutinesApi Coroutine features that may still change
FlowPreview Flow operators in preview

Treat these as signals, not obstacles. An @OptIn is a note that says "I read the docs, and this might change", which is exactly what a future you wants to find when upgrading.

Compiler flags

Everything so far was source code. The compiler also accepts options, passed by your build tool. In Gradle with the Kotlin DSL they go in the compilerOptions block. These examples are shown read-only because the in-browser runner compiles with fixed settings:

Kotlin
// build.gradle.kts (read-only example)
kotlin {
    compilerOptions {
        allWarningsAsErrors.set(true)
        optIn.add("kotlin.ExperimentalStdlibApi")
        freeCompilerArgs.add("-Xjsr305=strict")
    }
}

Compiler arguments fall into three groups:

  • Standard options, such as -language-version, -api-version, -jvm-target and -Werror. They are stable and documented.
  • Advanced options starting with -X, such as -Xjsr305=strict. They are supported but may change between versions.
  • Experimental or internal options starting with -XX. You rarely need them and they can disappear without notice.

A few you will actually see:

Option What it does
-Werror (allWarningsAsErrors) Turns every warning into an error; common on CI
-Xopt-in=pkg.Marker (or optIn in Gradle) Opts in globally, so you need no annotations in code
-language-version 2.3 Accepts only the language features of that version
-api-version 2.3 Prevents use of standard library APIs added later
-Xjsr305=strict Treats Java nullability annotations as real types for Kotlin
-progressive Enables stricter behavior that will become the default later

Be careful with a global opt-in flag. It silences the check everywhere, including places that should have been reviewed. Reserve it for markers you are sure about, and prefer @OptIn on specific declarations.

Language version and API version

Two numbers control compatibility, and they are independent:

  • The language version controls syntax and compiler behavior. Setting it to an older version lets a newer compiler reject features that the older one lacked.
  • The API version controls which standard library declarations you may call. Setting it older means your library does not accidentally require a newer runtime.

Library authors set both lower than the compiler version so that users with an older Kotlin can still build against the library. Application developers usually leave them at the default, which is the compiler's own version. You can read the version of the compiler that built the program at run time:

Kotlin Reading the Kotlin version

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

KotlinVersion.CURRENT reflects the standard library version in use, which is useful for tools and diagnostics, but you should not branch your program on it in normal code.

The K2 compiler

Since Kotlin 2.0, the default front end is K2, a rewrite of the part of the compiler that analyzes code (name resolution, type inference, smart casts). It replaced the older K1 front end. What changed for you:

  • Faster builds, especially for large projects.
  • Smarter smart casts: conditions combined with ||, local variables captured in lambdas that never change, and casts after try/when branches now work in more cases.
  • Cleaner multiplatform and tooling support: IDE features use the same engine as the command-line compiler, so what the editor shows matches what the build reports.
  • New features arrive on K2 only, including context parameters.

If an old project breaks after an upgrade, the usual causes are stricter type checks or removed deprecated APIs, not K2 bugs. Read the error, check the migration notes for your version, and fix the code rather than lowering the language version, which only postpones the problem.

Compiler flags change between Kotlin releases. When you copy a -X flag from an old blog post, check that it still exists. Unknown -X options are reported as a warning, and a flag for a feature that has since become stable is simply redundant and can be deleted.

A practical checklist

  1. Prefer @OptIn on the smallest declaration that needs it.
  2. Mark your own unstable APIs with a @RequiresOptIn marker and document what may change.
  3. Use level = ERROR for dangerous APIs.
  4. Turn on warnings as errors in CI, not necessarily on every developer's machine.
  5. Keep -language-version and -api-version at the default unless you publish a library for older users.
  6. Remove obsolete -X flags during upgrades.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What are the two ways to satisfy an opt-in requirement?

    You either mark your own declaration with the same marker (passing the decision on to your callers) or take responsibility with @OptIn so the requirement stops with you.
  2. 2. Which level of @RequiresOptIn makes the build fail if you ignore it?

    RequiresOptIn.Level has WARNING and ERROR. Ignoring an ERROR-level requirement is a compile error.
  3. 3. What does -api-version control?

    The API version restricts the standard library to a given release. The language version controls syntax and compiler behavior, and the JVM target is a separate option.
  4. 4. What is K2?

    K2 is the new front end for analysis, type inference and smart casts. It replaced K1 as the default in Kotlin 2.0.
  5. 5. Why prefer @OptIn on a single function over a global -Xopt-in flag?

    A narrow @OptIn documents exactly where you accepted the risk. A global flag removes the signal from the whole code base.

Summary

  • Opt-in lets API authors mark unstable or delicate declarations with a @RequiresOptIn marker; users must propagate the marker or write @OptIn(Marker::class).
  • Choose WARNING or ERROR as the level, use @SubclassOptInRequired to guard subclassing, and keep the opt-in scope small.
  • -Werror, -Xopt-in, -language-version, -api-version and -Xjsr305=strict are common compiler options, set through compilerOptions in Gradle.
  • Language version controls syntax; API version controls the available standard library.
  • K2 is the default compiler front end since 2.0 and brings faster builds and smarter smart casts.

Next: Building HTTP Servers and Clients with Ktor