DEV Community

Cover image for How to add opt-in compiler argument in build.gradle?
Vincent Tsen
Vincent Tsen

Posted on • Originally published at vtsen.hashnode.dev

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.

This article was originally published at vtsen.hashnode.dev on Jun 11, 2022.

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
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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
    /*...*/
}

Enter fullscreen mode Exit fullscreen mode

After that, I got this warning.

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

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"
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

[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 this 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
Enter fullscreen mode Exit fullscreen mode

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

See Also

Discussion (0)