Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
215: Meta-Annotations and Annotation Targets
I once spent an entire afternoon chasing a bug where a custom validation framework was simply ignoring half of the fields in a data class. The code looked perfect. The annotations were there, the reflection logic was sound, and the compiler wasn't complaining. The problem? I had forgotten that in Kotlin, a single line of code in a primary constructor can represent three different things: a constructor parameter, a class field, and a getter method.
annotation class Validated // No target specified
data class UserProfile(
@Validated val username: String,
@Validated val email: String
)
// A snippet of the reflection logic that was failing
fun validate(obj: Any) {
obj::class.members.forEach { member ->
// This was looking for annotations on the property/getter
if (member.annotations.any { it is Validated }) {
println("Validating ${member.name}...")
}
}
}
The Ambiguity of Constructor Properties
In the example above, I applied @Validated to username. But because I didn't specify a target, Kotlin didn't know exactly where that annotation should live. Depending on the compiler version and the specific context, it might have been applied to the constructor parameter, but not the actual field or the getter. When my validate function scanned the class members (the properties), it found nothing. The annotation was "invisible" because it was sitting on the constructor parameter, which isn't technically a member of the class.
This is a classic "silent failure." The code compiles because, by default, an annotation with no target can be placed almost anywhere. But in a professional codebase, that's actually a liability. You don't want developers putting a @JsonSerializable annotation on a local variable inside a function; it makes no sense and leads to runtime crashes.
Constraining the Target
To fix this, we use meta-annotations. A meta-annotation is simply an annotation that you apply to another annotation definition. The most important one here is @Target. By using AnnotationTarget, we can tell the compiler exactly where this annotation is allowed to exist.
@Target(AnnotationTarget.PROPERTY, AnnotationTarget.FIELD)
annotation class Validated
Now, if someone tries to put @Validated on a class or a local variable, the IDE will highlight it in red immediately. More importantly, by specifying AnnotationTarget.PROPERTY, we ensure the annotation is associated with the Kotlin property, making it visible to the reflection logic scanning obj::class.members.
You can provide multiple targets by passing them as a comma-separated list. I often do this when I want an annotation to work on both a function and the property that might hold its result.
Controlling the Lifecycle with Retention
While we're talking about meta-annotations, we have to mention @Retention. If you're writing a library or a framework that uses reflection, this is where things usually go sideways. There are three levels of retention:
AnnotationRetention.SOURCE: The annotation is discarded by the compiler. It's great for tools like Lint or for providing hints to the IDE, but it doesn't exist in the.classfile.AnnotationRetention.BINARY: The annotation is stored in the binary, but it's not visible via reflection at runtime.AnnotationRetention.RUNTIME: The annotation is stored in the binary and can be read by the JVM at runtime.
In Kotlin, the default is RUNTIME, but I always make it explicit. It documents the intent for anyone else reading my code—they'll know immediately that this annotation is intended to be processed by a reflection-based engine.
@Target(AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class Validated
I've seen developers use SOURCE for things they intended to check at runtime, only to spend hours wondering why member.annotations was returning an empty list. Always double-check your retention if your reflection logic is coming up empty.
📋 Practical Task
Build a Role-Based Access Control (RBAC) Annotation System
You are building a security module for a backend service. Your goal is to create an annotation called @RequiresRole that can only be applied to functions. This annotation should take a String parameter representing the required role (e.g., "ADMIN", "EDITOR").
Requirements:
- Create the
@RequiresRoleannotation. - Use meta-annotations to ensure it can only be applied to functions (
AnnotationTarget.FUNCTION). - Set the retention to
RUNTIME. - Create a class
ApiServicewith two functions:deleteUser()(marked as "ADMIN") andviewDashboard()(marked as "USER"). - Write a function called
checkAccess(service: Any, functionName: String, userRole: String)that uses reflection to:- Find the function by its name within the provided service object.
- Check if the
@RequiresRoleannotation is present. - If present, compare the required role with the
userRole. - Print "Access Granted" or "Access Denied".
Bonus Challenge: Try applying @RequiresRole to a class property and observe how the compiler prevents you from doing so.
There are no comments for now.