Kotlin AnnotationsAnnotations 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-annotationsWe can add meta-info while declaring annotation. Following are some meta-annotations:
Example of using annotationDeclaring an annotationAnnotation is declared by placing annotation modifier in front of a class. Annotate a constructorIt 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 assessorsUsing constructor as annotationWe 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 annotationCreating a java annotation interface Ann.java Create a MyClass.kt class which uses the annotation interface Ann. Output: Value: 10 Next TopicKotlin Reflection |