Kotlin Tutoial

Basics

Control Flow

Array & String

Functions

Collections

OOPs Concept

Exception Handling

Null Safety

Regex & Ranges

Java Interoperability

Miscellaneous

Android

Kotlin annotations

Annotations are a way to attach metadata to code in Kotlin, similar to other languages like Java. This metadata can then be read at runtime or compile-time to influence the behavior of the code or how it's treated. In this tutorial, we'll go over the basics of using annotations in Kotlin and also touch on some built-in Kotlin annotations.

1. Basic Annotation:

To use an annotation, you prefix its name with the @ symbol.

@Target(AnnotationTarget.CLASS)
annotation class MyAnnotation

2. Applying an Annotation:

Here's how you might apply the MyAnnotation from above to a class:

@MyAnnotation
class MyClass

3. Annotation Parameters:

Annotations can have parameters. They can be:

  • Primitive types (e.g., Int, Double)
  • Strings
  • Classes (KClass type in Kotlin)
  • Enums
  • Other annotations
  • Arrays of the types mentioned above

Here's an example:

annotation class MyAnnotationWithParams(val value: Int, val name: String)

Applying it:

@MyAnnotationWithParams(5, "Hello")
class MyClass

4. Specifying Meta-Annotations:

These are annotations for annotations. They provide meta-level behaviors:

  • @Target �� Specifies the possible kinds of elements which can be annotated with the annotation (e.g., class, function, property).
  • @Retention �� Specifies whether the annotation is stored in the compiled class files and whether it's visible at runtime.
  • @Repeatable �� Indicates that the annotation can be used multiple times on the same element.
  • @MustBeDocumented �� Marks the annotation as part of the public API, so it should be included in the class or method's generated documentation.

Example:

@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class MyAnnotation

5. Built-in Kotlin Annotations:

Kotlin provides a suite of annotations for various purposes. Here are a few:

  • @JvmStatic: Specifies that an additional static method needs to be generated from this element if it's a function. Mostly used in companion objects.

  • @JvmField: Indicates that the Kotlin property should be exposed as a field without getters or setters.

  • @JvmOverloads: Instructs the Kotlin compiler to generate overloads for this function that substitute default parameter values.

  • @Throws: This annotation indicates what exceptions should be declared by a function when compiled to a JVM method.

6. Using Annotations from Reflection:

To use annotations at runtime, you typically employ reflection:

val annotations = MyClass::class.annotations
for (annotation in annotations) {
    println(annotation.annotationClass.simpleName)
}

Conclusion:

Annotations in Kotlin offer a powerful way to augment your code with metadata that can be leveraged by frameworks, libraries, or the compiler. They're essential for interoperability with Java libraries and frameworks, but also have a range of uses purely within Kotlin codebases, especially when paired with Kotlin-specific tools and libraries.

  1. Creating custom annotations in Kotlin: Kotlin allows you to define custom annotations using the annotation class keyword.

    annotation class MyAnnotation
    
  2. Built-in annotations in Kotlin: Kotlin comes with several built-in annotations such as @JvmStatic, @JvmOverloads, @Nullable, and @Suppress.

    @JvmStatic
    fun myFunction() { /* ... */ }
    
  3. Annotation processing in Kotlin: Annotation processing involves inspecting and generating code based on annotations. Libraries like KotlinPoet can be used for annotation processing.

  4. Retention and targeting in Kotlin annotations: Use @Retention to specify how long the annotation should be retained (e.g., source, binary, runtime). Use @Target to specify where the annotation can be applied (e.g., class, function, property).

    @Retention(AnnotationRetention.RUNTIME)
    @Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
    annotation class MyAnnotation
    
  5. Using annotations for code generation in Kotlin: Annotations can be used to trigger code generation during the compilation process. Libraries like KAPT (Kotlin Annotation Processing Tool) can assist in this process.

  6. Annotations vs modifiers in Kotlin: Annotations provide metadata about the code, while modifiers (e.g., public, private) affect the visibility and behavior of code.

  7. Annotation parameters in Kotlin: Annotations can have parameters that allow customization when applied.

    annotation class MyAnnotation(val value: String)
    
  8. Meta-annotations in Kotlin: Meta-annotations are annotations applied to other annotations. For example, @Target and @Retention are meta-annotations.

  9. Library and framework annotations in Kotlin: Many libraries and frameworks use annotations for configuration and to provide additional information to tools.

  10. Documenting code with annotations in Kotlin: Annotations can be used for documentation purposes, providing additional information for tools like Dokka.

    /**
     * @param name The name of the person.
     */
    fun greet(name: String) { /* ... */ }
    
  11. Testing and debugging with Kotlin annotations: Annotations can be used to mark test functions, specify test configurations, or assist in debugging.

    @Test
    fun myTest() { /* ... */ }