How to Create Custom Annotation in Kotlin: Syntax and Example
In Kotlin, you create a custom annotation using the
annotation class keyword followed by the annotation name. You can add parameters inside the annotation class to pass values when using the annotation.Syntax
To create a custom annotation in Kotlin, use annotation class followed by the annotation name. You can define parameters inside parentheses if needed. Annotations can be applied to classes, functions, properties, etc.
Example parts:
annotation class: declares the annotationAnnotationName: the name of your annotation- Parameters (optional): define values to pass when using the annotation
kotlin
annotation class MyAnnotation(val info: String)Example
This example shows how to create a custom annotation with a parameter and how to apply it to a class. It also demonstrates how to access the annotation value using reflection.
kotlin
annotation class Info(val author: String) @Info(author = "Alice") class Book { fun printAuthor() { val annotation = this::class.annotations.find { it is Info } as? Info println("Author: ${annotation?.author}") } } fun main() { val book = Book() book.printAuthor() }
Output
Author: Alice
Common Pitfalls
Common mistakes when creating custom annotations include:
- Forgetting to use
annotation classkeyword and usingclassinstead. - Not specifying parameters correctly or missing default values if needed.
- Trying to use annotations without importing or enabling reflection when accessing them.
Annotations are metadata and do not change program behavior unless processed.
kotlin
/* Wrong: Using class instead of annotation class */ class WrongAnnotation(val info: String) // This is a normal class, not an annotation /* Right: Use annotation class */ annotation class CorrectAnnotation(val info: String)
Quick Reference
| Concept | Description |
|---|---|
| annotation class | Keyword to declare a custom annotation |
| Parameters | Optional values passed to the annotation |
| @AnnotationName | How to apply the annotation |
| Reflection | Used to read annotation values at runtime |
Key Takeaways
Use
annotation class to define a custom annotation in Kotlin.Annotations can have parameters to pass information when applied.
Apply annotations with
@AnnotationName before classes or functions.Access annotation data at runtime using Kotlin reflection.
Annotations are metadata and require processing to affect behavior.