Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to apply a single annotation to multiple use-site targets in Kotlin?

According to the documentation: https://kotlinlang.org/docs/reference/annotations.html

You can apply multiple annotations to a single site-use target, but is there a way to apply the same annotation to multiple site-use targets?

My use-case is decorating classes with annotations for SimpleXML. To use an immutable data class, you have to annotate both the field and the constructor parameter:

data class Data( @field:Element(name = "ID") @param:Element(name = "ID") val id: Int, @param:Element(name = "TEXT") @field:Element(name = "TEXT") val text: String)

For data classes with many fields, you can easily end up with 3x as many annotations as actual code, and it would be nice to eliminate the duplication. This is especially annoying when you have to use a complicated annotation like ElementUnion which can be multiple lines on its own.

like image 647
bj0 Avatar asked Nov 02 '17 18:11

bj0


People also ask

Can we apply two annotations together?

It is also possible to use multiple annotations on the same declaration: @Author(name = "Jane Doe") @EBook class MyClass { ... } If the annotations have the same type, then this is called a repeating annotation: @Author(name = "Jane Doe") @Author(name = "John Smith") class MyClass { ... }

What is @GET annotation in Kotlin?

By prefixing the annotation with @get: the resulting bytecode will have the annotation on the generated getter function: // Decompiled from the resulting Kotlin Bytecode @SomeAnnotation @Nullable public final String getSomeProperty() { return this. someProperty; }

What is JvmName annotation?

The @JvmName annotation changes the name of a function in the bytecode.

How do you inherit annotations?

Annotations, just like methods or fields, can be inherited between class hierarchies. If an annotation declaration is marked with @Inherited , then a class that extends another class with this annotation can inherit it. The annotation can be overridden in case the child class has the annotation.


1 Answers

Unfortunately, as of Kotlin 1.3, there's no syntax for this use case

like image 112
Andrey Breslav Avatar answered Nov 07 '22 05:11

Andrey Breslav