androidengineers.Book a session

Best Practices and Code Quality

Opt-in APIs: @RequiresOptIn / @OptIn and stability levels

article15 minHard

Opt-in records an intentional compatibility choice

@RequiresOptIn marks an API whose use needs explicit acknowledgement. Consumers opt in locally or at an appropriate wider scope. This communicates risk; it does not make an unstable API stable.

@RequiresOptIn(message = "The planning policy may change")
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
annotation class ExperimentalPlanning

@ExperimentalPlanning
fun suggestedMinutes(): Int = 25

@OptIn(ExperimentalPlanning::class)
fun previewPlan(): String = "${suggestedMinutes()} minutes"

A narrow opt-in keeps the decision visible. Annotating a caller with the requirement marker can propagate the obligation to its consumers instead. Library authors should explain what may change and how users can migrate.

Do not confuse a warning-level marker, compiler language-feature stability, and a product's support guarantee. They describe different contracts.

Exercise

Remove the opt-in and inspect the diagnostic. Then propagate the requirement from a wrapper function and confirm its callers also need to acknowledge it.

Check: choose the smallest scope that reflects the real use of the experimental API.

Reference: Opt-in requirements

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Opt-in APIs: @RequiresOptIn / @OptIn and stability levels | Kotlin Core Programming | Android Engineers