Vincent Tsen
Posted on July 2, 2022
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.
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 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
So I did the same as above to get rid of the warnings.
Originally published at https://vtsen.hashnode.dev.
Posted on July 2, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.