0
0
KotlinHow-ToBeginner · 3 min read

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 annotation
  • AnnotationName: 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 class keyword and using class instead.
  • 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

ConceptDescription
annotation classKeyword to declare a custom annotation
ParametersOptional values passed to the annotation
@AnnotationNameHow to apply the annotation
ReflectionUsed 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.