Kotlin annotations

Annotations are a feature of Kotlin that allows the programmer to embed supplemental information into the source file. This information, however, does not changes the actions of the program. This information is used by various tools during both development and deployment.

Annotations contains the following parameters most frequently and these must be compile-time constants:

  • primitive types(Int,Long etc)
  • strings
  • enumerations
  • class
  • other annotations
  • arrays of the above-mentioned types

Applying Annotation –

We can apply annotation by putting its name prefixed with the @ symbol in front of a code element. For example, if we want to apply an annotation named Positive, we should write the following if we want to write annotation Pos

@Positive val i: Int

A parameter can be passed in parenthesis to an annotation similar to function call.

@Allowedlanguage("Koltin")

When an annotation is passed as parameter in another annotation, then we should omit the @ symbol. Here we have passed Replacewith() annotation as parameter.

@Deprecated("This function is deprecated, use === instead", ReplaceWith("this === other"))

When an annotation parameter is a class object, we should add ::class to the class name as:

@Throws(IOException::class)

Declaring Annotation –

To declare an annotation, the class keyword is prefixed with the annotation keyword. By their nature, declarations of annotation cannot contain any code. While declaring our custom annotations, we should specify to which code elements they might apply and where they should be stored.

The simplest annotation contains no parameters –

annotation class MyClass

An annotation that requires parameter is much similar to a class with a primary constructor –

annotation class Suffix(val s: String)

Annotate a constructor –

We can also annotate the constructor of a class. It can be done by using the constructor keyword for constructor declaration and placing the annotation before it.

class MyClass@Inject constructor(dependency: MyDependency) {  
//. . .   
}

Annotate a property –

We can annotate the properties of class by adding an annotation to the properties. In below example, we assume that an Lang instance is valid if the value of the name is either Kotlin or Java.

class Lang (
    @Allowedlanguages(["Java","Kotlin"]) val name: String)
}

Some in-built annotations –

Kotlin also provides certain in-built annotations, that are used to provide more attributes to user-defined annotations. To be precise, these annotations are used to annotate annotations.

@Target –
This annotation specifies the places where the annotated annotation can be applied such as classes, functions, constructors, type parameters, etc. When an annotation is applied to the primary constructor for a class, the constructor keyword is specified before the constructor.

Example to demonstrate @Target annotation

filter_none

edit
close

play_arrow

link
brightness_4
code

@Target(AnnotationTarget.CONSTRUCTOR, AnnotationTarget.LOCAL_VARIABLE)
annotation class AnnotationDemo2
  
class ABC @AnnotationDemo2 constructor(val count:Int){
    fun display(){
        println("Constructor annotated")
        println("Count is $count")
    }
}
fun main(){
    val obj =  ABC(5)
    obj.display()
    @AnnotationDemo2 val message: String
    message = "Hello"
    println("Local parameter annotated")
    println(message)
}

chevron_right


Output:

Constructor annotated
Count is 5
Local parameter annotated
Hello

@Retention –
This annotation specifies the availability of the annotated annotation i.e whether the annotation remains in the source file, or it is available at runtime, etc. Its required parameter must be an instance of the AnnotationRetention enumeration that has the following elements:

  • SOURCE
  • BINARY
  • RUNTIME

Example to demonstrate @Retention annotation:

filter_none

edit
close

play_arrow

link
brightness_4
code

//Specifying an annotation with runtime policy 
@Retention(AnnotationRetention.RUNTIME)
annotation class AnnotationDemo3 
  
@AnnotationDemo3 fun main(){
    println("Main function annotated")
}

chevron_right


Output:

Main function annotated

@Repeatable –
This annotation allows an element to be annotated with the same annotation multiple times. As per the current version of Kotlin 1.3, this annotation can only be used with the Retention Policy set to SOURCE.

Example to demonstrate @Repeatable

filter_none

edit
close

play_arrow

link
brightness_4
code

@Repeatable
@Retention(AnnotationRetention.SOURCE)
annotation class AnnotationDemo4 (val value: Int)
  
@AnnotationDemo4(4)
@AnnotationDemo4(5)
fun main(){
    println("Repeatable Annotation applied on main")
}

chevron_right


Output:

Repeatable Annotation applied on main


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.