Opt-in requirements

suggest change

Some APIs are usable but not final yet. The standard library, kotlinx.coroutines and kotlinx.serialization all ship experimental functions whose names or behavior may change in the next release. Kotlin doesn't hide them. Instead, it makes you say "I know this may change" before you use them. This is an opt-in requirement.

The mechanism has three parts:

You can use the same mechanism for your own libraries.

Versions:

All the examples below were compiled and run with Kotlin 2.4.21 on JDK 25. The coroutines examples use kotlinx-coroutines-core 1.11.0.

Using an experimental API

kotlin.uuid.Uuid is stable in Kotlin 2.4, but Uuid.generateV7() is still marked @ExperimentalUuidApi (see UUIDs). Call it without opting in:

import kotlin.uuid.Uuid

fun main() {
    val id = Uuid.generateV7()
    println(id)
}

The compiler refuses:

a1.kt:4:19: error: this declaration needs opt-in. Its usage must be marked with '@kotlin.uuid.ExperimentalUuidApi' or '@OptIn(kotlin.uuid.ExperimentalUuidApi::class)'
    val id = Uuid.generateV7()
                  ^^^^^^^^^^

The message tells you both ways out. @OptIn is the common one. You can put it on a function, a class, a property, a single statement or expression, or a whole file:

import kotlin.concurrent.atomics.AtomicInt
import kotlin.concurrent.atomics.ExperimentalAtomicApi
import kotlin.concurrent.atomics.incrementAndFetch
import kotlin.uuid.ExperimentalUuidApi
import kotlin.uuid.Uuid

// 1. on a single function
@OptIn(ExperimentalUuidApi::class)
fun newId(): Uuid = Uuid.generateV7()

// 2. several markers at once, for the whole class
@OptIn(ExperimentalUuidApi::class, ExperimentalAtomicApi::class)
class IdGenerator {
    private val count = AtomicInt(0)

    fun next(): Pair<Int, Uuid> = count.incrementAndFetch() to Uuid.generateV7()
}

fun main() {
    println(newId().toString().length)

    val gen = IdGenerator()
    gen.next()
    println(gen.next().first)

    // 3. on a single statement or expression
    @OptIn(ExperimentalUuidApi::class)
    val v4 = Uuid.generateV4()
    println(v4.toString()[14]) // version digit
}

Output:

36
2
4

AtomicInt comes from the multiplatform atomics in kotlin.concurrent.atomics, which are also still experimental. Race conditions uses them.

Keep the opt-in as narrow as you reasonably can. @OptIn on a function documents exactly where the experimental API is used. When the API changes, you know which code to look at.

Opting in for a whole file

When most of a file uses one experimental API, put @file:OptIn at the very top, before package and the imports:

@file:OptIn(ExperimentalUuidApi::class)

import kotlin.uuid.ExperimentalUuidApi
import kotlin.uuid.Uuid

fun orderId() = Uuid.generateV7()
fun eventId() = Uuid.generateV7()

fun main() {
    val a = orderId()
    val b = eventId()
    println(a < b)
}

Output:

true

kotlinx.serialization code often does this with @file:OptIn(ExperimentalSerializationApi::class). See JSON for examples of experimental serialization features.

Opting in for a whole module

To allow an experimental API everywhere in a module, pass the marker's fully qualified name to the compiler with -opt-in:

$ kotlinc -opt-in=kotlin.uuid.ExperimentalUuidApi Ids.kt -d ids.jar

In Gradle, add it to the compiler options:

// build.gradle.kts
kotlin {
    compilerOptions {
        optIn.add("kotlin.uuid.ExperimentalUuidApi")
        optIn.add("kotlinx.coroutines.ExperimentalCoroutinesApi")
    }
}

In a multiplatform project you can also set it per source set:

kotlin {
    sourceSets.all {
        languageSettings.optIn("kotlin.uuid.ExperimentalUuidApi")
    }
}

This is convenient but hides where the experimental API is used. It's a good fit for test source sets or for an API your whole module is built on. Compiler options in general, including language versions and preview language features, are covered in the article on Kotlin compiler versions and experimental features.

Opting in vs. propagating

There are two ways to accept an opt-in requirement, and they mean different things:

import kotlin.uuid.ExperimentalUuidApi
import kotlin.uuid.Uuid

// Propagating: callers of newOrderId() must opt in too
@ExperimentalUuidApi
fun newOrderId(): String = "order-" + Uuid.generateV7().toHexString()

// Opting in: the experimental use stays an implementation detail
@OptIn(ExperimentalUuidApi::class)
fun newEventId(): String = "event-" + Uuid.generateV7().toHexString()

fun main() {
    println(newEventId().length)
    println(newOrderId().length)
}
d1.kt:14:13: error: this declaration needs opt-in. Its usage must be marked with '@kotlin.uuid.ExperimentalUuidApi' or '@OptIn(kotlin.uuid.ExperimentalUuidApi::class)'
    println(newOrderId().length)
            ^^^^^^^^^^

newEventId() can be called freely. newOrderId() carries the requirement up to main. Propagate when experimental types show up in your own public signatures, for example when you return or accept an experimental class. If the experimental part is hidden inside the body, @OptIn is enough.

Compiled with -opt-in=kotlin.uuid.ExperimentalUuidApi, the program builds and prints:

38
38

Marking your own API

A marker is an ordinary annotation class with @RequiresOptIn on it. @RequiresOptIn takes two optional arguments:

Here is a small key-value store with one experimental function and one "delicate" function that skips validation:

// Markers for your own library
@RequiresOptIn(
    message = "The cache API is experimental and may change without notice.",
    level = RequiresOptIn.Level.WARNING,
)
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY)
annotation class ExperimentalCacheApi

@RequiresOptIn(
    message = "Raw access skips validation. Use Store.put() unless you know what you are doing.",
    level = RequiresOptIn.Level.ERROR,
)
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.FUNCTION)
annotation class DelicateStoreApi

class Store {
    private val data = mutableMapOf<String, String>()

    fun put(key: String, value: String) {
        require(key.isNotBlank()) { "blank key" }
        data[key] = value
    }

    fun get(key: String): String? = data[key]

    @ExperimentalCacheApi
    fun warmUp(keys: List<String>) = keys.forEach { data.getOrPut(it) { "" } }

    @DelicateStoreApi
    fun putRaw(key: String, value: String) {
        data[key] = value
    }
}

fun main() {
    val s = Store()
    s.put("a", "1")
    s.warmUp(listOf("b", "c"))
    s.putRaw("", "oops")
    println(s.get("a"))
}

The ERROR-level call stops compilation:

c1.kt:41:7: error: raw access skips validation. Use Store.put() unless you know what you are doing.
    s.putRaw("", "oops")
      ^^^^^^

Opt in to DelicateStoreApi on that one call and the program compiles, with a warning for the WARNING-level call:

    @OptIn(DelicateStoreApi::class)
    s.putRaw("", "oops")
c2.kt:40:7: warning: the cache API is experimental and may change without notice.
    s.warmUp(listOf("b", "c"))
      ^^^^^^
1

Notes:

See Declaring an annotation and Meta-annotations for annotation classes, @Retention and @Target in general.

Experimental classes and overrides

A marker on a class covers every use of the class, not only calls. Using it as a parameter type, accessing its properties and overriding a member that mentions it all count. Overriding an experimental member also requires an opt-in, even if your override doesn't use anything experimental.

@RequiresOptIn(message = "Metrics API is experimental.")
@Retention(AnnotationRetention.BINARY)
annotation class ExperimentalMetricsApi

@ExperimentalMetricsApi
class Histogram(val name: String) {
    private val values = mutableListOf<Double>()
    fun record(v: Double) { values += v }
    fun mean() = values.average()
}

interface Plugin {
    fun name(): String

    @ExperimentalMetricsApi
    fun report(h: Histogram) {}
}

class LoggingPlugin : Plugin {
    override fun name() = "logging"
    override fun report(h: Histogram) { println("${h.name}: ${h.mean()}") }
}

fun describe(h: Histogram) = h.name
e1.kt:21:18: error: base declaration of supertype 'Plugin' needs opt-in. Metrics API is experimental. The declaration override must be annotated with '@ExperimentalMetricsApi' or '@OptIn(ExperimentalMetricsApi::class)'
    override fun report(h: Histogram) { println("${h.name}: ${h.mean()}") }
                 ^^^^^^
e1.kt:21:28: error: metrics API is experimental.
    override fun report(h: Histogram) { println("${h.name}: ${h.mean()}") }
                           ^^^^^^^^^
e1.kt:21:52: error: metrics API is experimental.
    override fun report(h: Histogram) { println("${h.name}: ${h.mean()}") }
                                                   ^
e1.kt:21:63: error: metrics API is experimental.
    override fun report(h: Histogram) { println("${h.name}: ${h.mean()}") }
                                                              ^
e1.kt:24:17: error: metrics API is experimental.
fun describe(h: Histogram) = h.name
                ^^^^^^^^^
e1.kt:24:30: error: metrics API is experimental.
fun describe(h: Histogram) = h.name
                             ^

The declarations in the library that are themselves marked, like Plugin.report, don't need an opt-in to mention Histogram. The fixed version propagates the marker on the override and opts in in main:

class LoggingPlugin : Plugin {
    override fun name() = "logging"

    @ExperimentalMetricsApi
    override fun report(h: Histogram) {
        println("${name()} ${h.name}: ${h.mean()}")
    }
}

@OptIn(ExperimentalMetricsApi::class)
fun main() {
    val h = Histogram("latency_ms")
    listOf(12.0, 15.0, 30.0).forEach(h::record)
    val plugins: List<Plugin> = listOf(LoggingPlugin())
    for (p in plugins) p.report(h)
}

Output:

logging latency_ms: 19.0

@SubclassOptInRequired: safe to call, unsafe to implement

Some types are stable for callers but not for implementers. Adding a new abstract member to a public interface doesn't break code that calls it, but it breaks every class outside the library that implements it. Marking the whole interface with @RequiresOptIn would force every caller to opt in, which is too much.

@SubclassOptInRequired(Marker::class) puts the requirement only on inheritance. Using the type, calling its members and accepting it as a parameter need no opt-in. Implementing or extending it does:

@RequiresOptIn(
    message = "Shape may get new abstract members in any release.",
    level = RequiresOptIn.Level.ERROR,
)
@Retention(AnnotationRetention.BINARY)
annotation class ShapeImplementationApi

@SubclassOptInRequired(ShapeImplementationApi::class)
interface Shape {
    val name: String
    fun area(): Double
}

// The library's own implementations opt in
@OptIn(ShapeImplementationApi::class)
class Circle(private val r: Double) : Shape {
    override val name = "circle"
    override fun area() = Math.PI * r * r
}

@OptIn(ShapeImplementationApi::class)
class Square(private val side: Double) : Shape {
    override val name = "square"
    override fun area() = side * side
}

// Using Shape as a type and calling its members needs no opt-in
fun total(shapes: List<Shape>): Double = shapes.sumOf { it.area() }

fun describe(s: Shape) = "${s.name}: ${"%.2f".format(s.area())}"

fun main() {
    val shapes = listOf(Circle(1.0), Square(2.0))
    shapes.forEach { println(describe(it)) }
    println("total: %.2f".format(total(shapes)))
}

Output:

circle: 3.14
square: 4.00
total: 7.14

The requirement applies inside the declaring module too. Without the @OptIn on Circle, the compiler reports:

error: this class or interface requires opt-in to be implemented: Shape may get new abstract members in any release.
class Circle(private val r: Double) : Shape {
                                      ^^^^^

An interface that extends Shape has three choices: opt in, mark itself with the marker (making the whole interface experimental), or pass the inheritance requirement on with its own @SubclassOptInRequired. Anonymous objects count as implementations too:

@RequiresOptIn(level = RequiresOptIn.Level.ERROR)
@Retention(AnnotationRetention.BINARY)
annotation class ShapeImplementationApi

@SubclassOptInRequired(ShapeImplementationApi::class)
interface Shape { fun area(): Double }

// Propagate: subclasses of Polygon also need the opt-in
@SubclassOptInRequired(ShapeImplementationApi::class)
interface Polygon : Shape { val sides: Int }

@OptIn(ShapeImplementationApi::class)
class Hexagon(private val a: Double) : Polygon {
    override val sides = 6
    override fun area() = 3 * Math.sqrt(3.0) / 2 * a * a
}

// Anonymous objects need it too
@OptIn(ShapeImplementationApi::class)
val unit = object : Shape { override fun area() = 1.0 }

fun main() {
    println("%.3f".format(Hexagon(1.0).area()))
    println(unit.area())
}

Output:

2.598
1.0

@SubclassOptInRequired accepts several markers, for example @SubclassOptInRequired(A::class, B::class). An implementation then has to opt in to all of them.

kotlinx.coroutines uses this for Job, Flow-related interfaces such as StateFlow and SharedFlow, and others. Implementing StateFlow yourself gives a warning:

warning: this class or interface requires opt-in to be implemented: Inheriting from this kotlinx.coroutines API is unstable. Either new methods may be added in the future, which would break the inheritance, or correctly inheriting from it requires fulfilling contracts that may change in the future.
class ConstantFlow<T>(override val value: T) : StateFlow<T> {
                                               ^^^^^^^^^^^^

The marker there is ExperimentalForInheritanceCoroutinesApi. Job uses the stricter InternalForInheritanceCoroutinesApi. In practice, use MutableStateFlow and stateIn instead of implementing StateFlow (see Flows).

Opt-in requirements vs. @Deprecated

Both produce compiler warnings or errors at the use site, but they say opposite things:

@RequiresOptIn marker @Deprecated
Meaning "Not final yet. May change or disappear." "Old. Stop using it, it will be removed."
Direction API is moving toward stable API is moving toward removal
Acknowledge with @OptIn(Marker::class) or propagate the marker @Suppress("DEPRECATION")
Levels WARNING, ERROR WARNING, ERROR, HIDDEN
Replacement hint only in message replaceWith = ReplaceWith(...), which the IDE can apply
Granularity one marker groups a whole feature area each declaration separately
Inheritance-only variant @SubclassOptInRequired none

A typical library API lifecycle uses both: new API ships behind a marker, the marker is removed when the API is stable, and much later the old API it replaced gets @Deprecated with a ReplaceWith. Comments and documentation shows @Deprecated in detail.

When an API graduates, existing @OptIn annotations for it become no-ops. They don't produce warnings, so you can remove them at your own pace. That's why @OptIn(ExperimentalTime::class) on kotlin.time.Clock code still compiles on Kotlin 2.4 even though Clock and Instant are stable now. If you publish a library, keep the marker class around after the API is stable. Deleting it turns every @OptIn(YourMarker::class) in your users' code into an unresolved reference.

Common markers

Marker Package Level Used for
ExperimentalStdlibApi kotlin ERROR assorted new stdlib functions
ExperimentalUnsignedTypes kotlin WARNING UByteArray, UIntArray and friends
ExperimentalUuidApi kotlin.uuid ERROR Uuid.generateV4(), generateV7()
ExperimentalAtomicApi kotlin.concurrent.atomics ERROR multiplatform AtomicInt, AtomicReference
ExperimentalEncodingApi kotlin.io.encoding ERROR Base64 stream wrappers (see Base64 and hex encoding)
ExperimentalCoroutinesApi kotlinx.coroutines WARNING flatMapLatest, mapLatest and others
FlowPreview kotlinx.coroutines WARNING debounce, sample and others
DelicateCoroutinesApi kotlinx.coroutines WARNING GlobalScope, newSingleThreadContext
ExperimentalSerializationApi kotlinx.serialization WARNING @JsonNames, naming strategies, streaming

The levels and the set of experimental declarations change between releases, so trust the compiler message over any list. Where a WARNING-level marker is involved the compiler says the usage "should be marked". For ERROR it says "must be marked":

warning: this declaration needs opt-in. Its usage should be marked with '@kotlin.ExperimentalUnsignedTypes' or '@OptIn(kotlin.ExperimentalUnsignedTypes::class)'

Summary

Task Code
use an experimental API in one place @OptIn(Marker::class) on the function, class or statement
several markers @OptIn(A::class, B::class)
whole file @file:OptIn(Marker::class) before package
whole module -opt-in=pkg.Marker / Gradle compilerOptions { optIn.add("pkg.Marker") }
make your function experimental too annotate it with @Marker
declare a marker @RequiresOptIn(message = "...", level = ...) + @Retention(BINARY) on an annotation class
allow calling but not implementing @SubclassOptInRequired(Marker::class) on the interface or open class
implement such a type @OptIn(Marker::class) or propagate with @SubclassOptInRequired(Marker::class)

Prefer the narrowest @OptIn that works. Propagate the marker when experimental types appear in your public API. Use @SubclassOptInRequired for interfaces you want people to call but not implement.

Feedback about page:

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



Table Of Contents