How to use annotations in Kotlin?
sobes.tech AI
Answer from AI
Annotations in Kotlin are used to add metadata to classes, properties, functions, expressions, and parameters. They do not perform direct actions but can be used by the compiler, frameworks, or other libraries for various processing.
Main aspects of usage:
-
Syntax: Annotations are placed before the element they apply to, prefixed with
@. If an annotation has parameters, they are specified in parentheses after the name.@Deprecated("Use newFunction instead") fun oldFunction() { // ... } @JvmStatic fun staticMethod() { // ... } -
Application to various elements: Annotations can be applied to:
- Classes (
class):@Serializable class User(val name: String) - Properties (
val,var):@Inject lateinit var userRepository: UserRepository - Functions (
fun):@Test fun testSomething() { // ... } - Constructor/function parameters:
fun processUser(@NotNull user: User) { // ... } - Expressions:
fun calculate(@Ignore parameter: Int) { // ... } - Types (
@Target(AnnotationTarget.TYPE)):val list: @NotNull List<String> = emptyList()
- Classes (
-
Use-site Targets: To disambiguate which element an annotation applies to when there are multiple (e.g., field and getter), use-site targets are used.
Target Description @file:Applies to the entire file @property:Applies to the property as a whole @field:Applies to the backing field @get:Applies to the property getter @set:Applies to the property setter @param:Applies to constructor parameters @setparam:Applies to setter parameters @delegate:Applies to the delegate instance @receiver:Applies to the receiver type class Example(@field:Inject val dependency: Dependency) { // @field:Inject applies to the 'dependency' field } -
Declaring custom annotations: Custom annotations are declared with the
annotation classkeyword. Annotation parameters can be primitive types, strings, classes (KClass), enums, other annotations, or arrays of these types.annotation class MyAnnotation(val value: String, val count: Int = 0) @MyAnnotation("Hello", count = 5) class AnnotatedClass { // ... } -
Meta-annotations: Annotations can be marked with meta-annotations that define their behavior and applicability.
@Target: Specifies which elements can be annotated.@Retention: Specifies at which stage the annotation is retained (SOURCE,BINARY,RUNTIME).@Repeatable: Allows applying the annotation multiple times to the same element.@MustBeDocumented: Indicates that the annotation should be part of the public API generated by documentation tools.
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION) @Retention(AnnotationRetention.RUNTIME) annotation class ProcessedByFramework
Annotations are widely used in Kotlin for integration with JVM frameworks (Spring, Android), serialization (Kotlinx.serialization), testing (JUnit), and creating custom libraries based on metadata.