Declaration
An annotation is defined using theannotation modifier preceding a class declaration. Annotation classes can contain a body, but the language strictly limits its contents. They can include companion objects, nested classes, interfaces, and objects, but cannot contain functions, init blocks, or properties outside the primary constructor.
Meta-Annotations
The behavior and scope of an annotation are configured using meta-annotations (annotations applied to the annotation class itself).@Target: Defines the syntactic elements to which the annotation can be applied (e.g.,CLASS,FUNCTION,PROPERTY,EXPRESSION).@Retention: Determines the lifecycle of the annotation.SOURCE: Discarded by the compiler; not present in the compiled binary.BINARY: Stored in the compiled class file but not visible via reflection at runtime.RUNTIME: (Default) Stored in the compiled class file and accessible via runtime reflection.
@Repeatable: Permits the annotation to be applied multiple times to the same element.@MustBeDocumented: Instructs documentation generation tools (like Dokka) to include the annotation in the public API signature.
Constructors and Parameters
Annotations can accept parameters via a primary constructor. All parameters must be declared as read-only (val).
The type system strictly limits annotation parameters to the following:
- Primitive types (
Int,Double,Boolean, etc.) String- Classes (
KClass) - Enums
- Other annotations
- Arrays of the aforementioned types
java.lang.Class) are strictly prohibited.
Application Syntax
Annotations are applied by prefixing the target element with the@ symbol, followed by the annotation name and any required constructor arguments.
@ prefix is omitted for the nested annotation.
Use-Site Targets
Because a single Kotlin property declaration can generate multiple Java bytecode elements (a backing field, a getter, a setter, and a constructor parameter), Kotlin provides use-site targets to explicitly specify which generated element receives the annotation. The syntax follows the pattern@target:AnnotationName.
Supported use-site targets include:
file: Applies to the entire file (must be placed at the top of the file, beforepackage).property: Applies to the Kotlin property (invisible to Java reflection).field: Applies to the generated Java backing field.get/set: Applies to the generated property getter or setter.receiver: Applies to the receiver parameter of an extension function or property.param: Applies to the constructor parameter.setparam: Applies to the parameter of the property setter.delegate: Applies to the field storing the delegate instance for a delegated property.
Expression and Lambda Annotations
Annotations can be applied directly to expressions or lambda functions, provided the annotation’s@Target explicitly includes AnnotationTarget.EXPRESSION.
Tired of Poor Kotlin Skills? Fix That With Deep Grasping!Learn More





