Rens
Rens

Reputation: 518

Kotlin custom annotation, arguments

I'm trying to create a custom annotation with an array of arguments but I get an error when trying to set the arguments in the constructor of the annotation. It says it is expecting a type annotation on the Role[], while, if i'm right the Role[] is the type. I looked up the syntax in the docs which can be found here: https://kotlinlang.org/docs/reference/annotations.html. But this documentation only explains how I can use the annotation and not how to create one.

This is what my annotation code looks like:

@NameBinding
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class Secured(vararg val value: Role[])

This is what my Role class looks like:

enum class Role {
   ADMIN, USER
}

and this is how I want to use it:

@Secured(Role.ADMIN, Role.USER)

I tried looking for any examples on how to create annotations in Kotlin but I can't seem to find any weirdly. Anyone who can help me out?

Upvotes: 9

Views: 13516

Answers (1)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

The following compiles:

enum class Role { ADMIN, USER }

annotation class Secured(vararg val value: Role)

@Secured(Role.ADMIN, Role.USER)
fun foo() {}

As does this:

enum class Role { ADMIN, USER }

annotation class Secured(val value: Array<Role>)

@Secured([Role.ADMIN, Role.USER])
fun foo() {}

They compile to the same bytecode, but Kotlin demands that you use slightly different syntax to instantiate the annotation.

Upvotes: 15

Related Questions