Skip to main content

Command Palette

Search for a command to run...

How to add opt-in compiler argument in build.gradle?

Some APIs want you to specify @OptIn() annotation in order to use them, and you also need to add opt-in compiler argument in your build.gradle file.

Updated
2 min read
How to add opt-in compiler argument in build.gradle?
V

I'm a self-taught hobbyist Android developer who loves to build projects and share valuable tips for new Android developers.

Feel free to comment, share or connect with me!

When I tried to use androidx.compose.ui.platform.LocalSoftwareKeyboardController in my RSS Feed Reader app, it turned out it is an @ExperimentalComposeUiApi which has this @RequiresOptIn() annotation.

@RequiresOptIn("This API is experimental and is likely to change in the future.")
annotation class ExperimentalComposeUiApi

That means, in order to use this LocalSoftwareKeyboardController, I need to add @OptIn() annotation in the class or else you will see a warning/error like below which is defined by the RequiresOptIn() annotation above.

This API is experimental and is likely to change in the future.

So, I added this @OptIn(ExperimentalComposeUiApi::class).

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun ArticlesTopBar(
    navHostController: NavHostController,
    viewModel: MainViewModel,
    onArticlesSearch: () -> Unit,
) {
    val keyboardController = 
    val keyboardController = LocalSoftwareKeyboardController.current
    /*...*/
}

After that, I got this warning.

Warning:(21, 6) This class can only be used with the compiler argument '-opt-in=kotlin.RequiresOptIn'

To fix this warning, I added this compiler argument in the build.gradle (module level) based on the official documentation here.

android {

    /*...*/

    tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
        kotlinOptions {
            freeCompilerArgs += "-Xopt-in=kotlin.RequiresOptIn"
        }
    }
}

[Updated: July 01, 2022] - It looks like this -Xopt-in=kotlin.RequiresOptIn compiler argument is not needed anymore in Kotlin 1.7.0. See here.

While developing same Simple REST API app, I also encountered the same issue because the APIs from com.jakewharton.retrofit2.converter.kotlinx.serialization packages are marked with @ExperimentalSerializationApi annotation, which requires me to specify the@OptIn() annotation.

@RequiresOptIn(level = RequiresOptIn.Level.WARNING)
public annotation class ExperimentalSerializationApi

So I did the same as above to get rid of the warnings.

Android Studio

Part 8 of 17

From setup to advanced features, discover everything you need to know to take your skills to the next level with Android Studio.

Up next

Missing Run Test in Android Studio

Manually edit run configuration as workaround for missing run test in Android Studio Bumblebee