This is the error I get when using custom annotation in a higher-order function:
Is there any way to use annotations in higher-order functions? If not, what would be an alternative solution (apart from using enums)?
This is how my custom annotation looks like:
companion object {
private const val PERMISSION_DENIED = 1
private const val PROVIDER_DISABLED = 2
private const val SUCCESS = 3
@IntDef(PERMISSION_DENIED, PROVIDER_DISABLED, SUCCESS)
@Retention(AnnotationRetention.SOURCE)
annotation class PreconditionResult
}
Workaround
There's a workaround which involves functional interfaces (notice the fun interface
below).
Note: Unfortunately, functional interfaces that are defined in kotlin code are only available since the upcoming 1.4 release. You can test it now with 1.4-M1
.
fun interface FulFilled {
fun execute(@PreconditionResult fulFilled: Int): Unit
}
private fun checkPrecondition(context: Context, fulFilled: Fulfilled) {
}
checkPrecondition(context) { fulFilled -> println("Got $fulFilled")}
Possible solution
I'm not sure if it would achieve what you need to, but it's also possible to drop the argument name from your type definition:
private fun checkPrecondition(context: String, callback: (@PreconditionResult Int) -> Unit) {
You'll need to change the target of your annotation to a type:
@Retention(AnnotationRetention.SOURCE)
@Target(AnnotationTarget.TYPE)
annotation class PreconditionResult
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.