ZeitPolizei
ZeitPolizei

Reputation: 531

How can I avoid repeating the same annotation arguments everywhere?

I'm using an annotation from a library that requires a list of arguments, and there are a lot of classes throughout my project that use this annotation with those exact same arguments.

@AnnotationFromDependency(values = [long, list, of, variables, that, might, change])
class Foo {
    fun bar() {
        println("dostuff")
    }
}

How can I avoid copying the same arguments for @AnnotationDependency to every class that uses it? Defining the arguments list in a variable does not work because it is not a compile-time constant.

val myValues = arrayOf("long", "list", "of", "values", "that", "might", "change")

@AnnotationFromDependency(values = myValues) // error: An annotation argument must be a compile-time constant
class Foo {
    fun bar() {
        println("dostuff")
    }
}

Upvotes: 1

Views: 460

Answers (1)

Jakub Zalas
Jakub Zalas

Reputation: 36191

Define a custom annotation and annotate it with the third-party one:

@AnnotationFromDependency(values = ["long", "list", "of", "variables", "that", "might", "change"])
annotation class MyAnnotation()

Note: Meta-annotations are annotations applied to other annotations.

Next, use your annotation instead of the third party one where needed:

@MyAnnotation
class Foo()

If you ever need to modify the list of values you will only need to do it in one place.

Upvotes: 4

Related Questions