You are relying on JVM reflection and it is different that kotlin’s reflection
Kotlin does not translate 1-1 to Java.
Fields in kotlin are called properties and are translated into
multiple components, a getter, setter and a backing field (depending on the declaration)
This way, a property can be overriden, delegated and/or have a custom setter/getter
When a property is annotated, since java doesn’t have such element (kotlin properties), the annotation isn’t translated to java. And kotlin doesn’t know what component to annotate. The getter? the setter? or the backing field?
It is needed to guide kotlin on what component should be annotated. Or rely on the default kotlin behavior.
And that is why sometimes it is needed to tell kotlin to explicitly annotate the backing field.
@Target(AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
annotation class ExampleAnnotation
class ExampleClass {
@ExampleAnnotation
val exampleProperty: String = ""
}
fun main() {
val clazz = ExampleClass::class.java
clazz.declaredFields.forEach { field ->
println(field.annotations.map { it is ExampleAnnotation })
}
}
I didn’t knew about this exact behavior.
In my defense, the question was about why it is needed to add @field: and not is it always necessary.
But, I am so sorry for the false statement in my first answer