Skip to main content
An annotation class in Kotlin is a specialized class used to attach metadata to declarations and expressions. It acts as a declarative marker that can be processed by the compiler, development tools, or at runtime via reflection, without directly altering the execution logic of the annotated code.

Syntax and Declaration

An annotation class is defined using the annotation modifier preceding the class keyword.

Constructor Constraints

Annotation classes have strict structural limitations enforced by the Kotlin compiler. If an annotation class defines a primary constructor, its parameters must adhere to the following rules:
  • All parameters must be declared as read-only (val).
  • Parameters cannot be nullable.
  • Default values are permitted and must be compile-time constants.
Allowed Parameter Types:
  • Primitive types (Int, Long, Double, Boolean, etc.)
  • String
  • Classes (KClass)
  • Enums
  • Other annotation classes
  • Arrays of the types listed above

Meta-Annotations

The behavior, visibility, and applicability of an annotation class are governed by meta-annotations—annotations applied directly to the annotation class declaration.

@Target

Specifies the syntactic entities to which the annotation can be applied. It accepts one or more AnnotationTarget enum values.

@Retention

Determines the lifecycle of the annotation, dictating whether it is discarded or retained in the compiled output. It accepts an AnnotationRetention enum value:
  • SOURCE: Discarded by the compiler; not present in the compiled binary.
  • BINARY: Stored in the compiled class files but not visible through runtime reflection.
  • RUNTIME (Default): Stored in the compiled class files and accessible at runtime via reflection.

@Repeatable

Allows the same annotation to be applied multiple times to a single element.

@MustBeDocumented

Instructs documentation generation tools (like Dokka) to include the annotation in the generated public API documentation of the annotated elements.

Instantiation Mechanics

Annotations are primarily instantiated by applying them to code elements using the @ symbol. When applying an annotation that requires a class reference, Kotlin uses the ::class syntax.
If an annotation is used as a parameter within another annotation, the @ prefix is omitted for the nested annotation.
Since Kotlin 1.5.30, annotation classes can also be instantiated directly using standard object creation syntax by calling their constructors. This is particularly useful when working with reflection, custom metadata processing, or generating annotations dynamically.
Tired of Poor Kotlin Skills? Fix That With Deep Grasping!Learn More