Kotlin annotations

Kotlin's annotation functionality enables programmers to incorporate extra information directly into source files. However, the program's actions remain unchanged as a result of this information. Several tools use this data for deployment as well as development of Mobile application.

Applying Annotation

We can use annotation by prefixing its name with the @ sign in front of a code element. For example, if we wish to use an annotation named Positive, we should write the following:

 @Positive val i: Int

A parameter can be passed in parenthesis function call.

 @Allowedlanguage("Kotlin")

We should return the @ sign. We have supplied the Replacewith() annotation as an argument.

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

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

  @Throws(IOException::class)

Declaring Annotation

Code cannot be included in annotation declarations. When declaring custom annotations, we should describe which code components they may apply to and where they should be saved. 

 annotation class MyClass

an annotation that requires parameter mentioned below

 annotation class Suffix(val s: String)

Annotate a constructor

We can also annotate the constructor of a class.

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

Annotate a property

We can annotate the properties of the class by adding an annotation to them.

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

Example 

  @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)
  }

Output

 Constructor annotated
 Count is 5
 Local parameter annotated
 Hello
365Bloggy June 18, 2024
Share this post
Tags
SUBSCRIBE THIS FORM


Archive