Javatpoint Logo
Javatpoint Logo

Kotlin Annotations

Annotations are used to attach metadata to classes, interface, parameters, and so on at compile time. Annotation can be used by compiler which reflects at runtime. We can change the meaning of the data or program according to annotation values.

Kotlin Meta-annotations

We can add meta-info while declaring annotation. Following are some meta-annotations:

Annotation Name Usage
@Target It targets all the possible kinds of elements which can be annotated with the annotation.
@Retention It specifies whether the annotation is stored in the compiled class files or whether it is visible through reflection at run time.
@Repeatable This meta-annotation determines that an annotation is applicable twice or more on a single code element.
@MustBeDocumented This meta-document specifies that the annotation is the part of the public API and should be included in the class or method.

Example of using annotation

Declaring an annotation

Annotation is declared by placing annotation modifier in front of a class.

Annotate a constructor

It is also possible to annotate the constructor of a class. This is done by adding the constructor keyword for constructor declaration and placing the annotation before it.

Annotate property assessors

Using constructor as annotation

We can also use constructor as an annotation. Using constructor as annotation takes parameters.

The parameters which are used as an annotation cannot be nullable types. This is because the JVM does not support null as a value for an annotation attribute.

We can also use one annotation as a parameter to another annotation, at such situation it cannot takes the prefix @ character. Forexample:

Kotlin also specifies that a class can takean argument of an annotation by using a KClass. The Kotlin compiler automatically converts it into java class, which leads to see the annotations and arguments normally.

Example of using TYPE annotation

Creating a java annotation interface Ann.java

Create a MyClass.kt class which uses the annotation interface Ann.

Output:

Value: 10

Next TopicKotlin Reflection





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA