Annotations in Kotlin


Annotations in Kotlin

An annotation is a code feature that allows the programmer to embed relevant information in the source file. However, this information does not change the operation of the program. Various tools use this information in development and deployment. Annotations most commonly include the following parameters, which must be compile-time constants:

  • The primitive data types such as int, long, float, double, etc.
  • Strings, Enumerations, and Classes.
  • Arrays of the above-mentioned data types.
  • The other annotations.

Applying Annotations in kotlin

We can apply the annotations by prefixing a code element with the symbol in front of its name. A parameter in parentheses can be transferred to an annotation similar to a function call. When giving an annotation as a parameter in another annotation, we must avoid the @ symbol. Here we have passed the Replacewith () annotation as a parameter.

Declaring Annotation

The class keyword is prefixed with the comment keyword to declare an annotation. By their very nature, commentary declarations should not contain any code. When announcing our custom annotations, we must specify which code elements should be applied and where they should be stored. The most straightforward annotation contains no parameters, and an annotation that requires a parameter is similar to a class with a primary constructor.

To annotate a constructor - To define the constructor of a class can be done by using the constructor keyword for the constructor declaration and placing the annotation in front of it.

To annotate a property - We can annotate the class's attributes by adding a commentary on the attributes.

Some built-in annotations

Kotlin also provides some in-built interpretations that can be used to add additional attributes to user-defined annotations. T be precise, these annotations are used to interpret annotations.

@Target Annotation - This annotation specifies the areas where the annotation can be applied, such as classes, functions, constructors, type parameters, etc. When using an annotation to the primary constructor for a class, the constructor specifies the keyword before the constructor.

@Retention Annotation - This annotation specifies the availability of the annotated annotation, i.e., whether the annotation exists in the source files or is available in runtime, and so on. Its required parameter should be an example of an AnnotationRetention enumerator with the following components:

  • Source
  • Binary
  • Runtime

@Repeatable Annotation - This annotation allows a component to be interpreted multiple times in the same annotations. According to the current version of Kotlin 1.3, this annotation can only be used on the retention policy set as the source.