Annotations on var/val parameters

If I use kotlin-reflect to try something like this:

import kotlin.reflect.full.*

annotation class Annotation(val baz: Int)

data class Foo(@Annotation(3) val bar: Int)

fun main(args: Array<String>) {
    val primaryConstructor = Foo::class.primaryConstructor!!
    for (property in Foo::class.memberProperties) {
        println("Property ${property.name} has annotations ${property.annotations}")
    }
    for (param in primaryConstructor.parameters) {
        println("Parameter ${param.name} has annotations ${param.annotations}")
    }
}

I get

Property foo has annotations [@Annotation(baz=3)]
Parameter foo has annotations []

IMO the parameter (which becomes a property) should somehow be treated as both because it is a parameter.
I found the @property:Annotation syntax, but I find this very repetitive:

e.g.

data class Foo(@property:Annotation(3) @Annotation(3) bar: Int)

This gives the expected

Property bar has annotations [@Annotation(baz=3)]
Parameter bar has annotations [@Annotation(baz=3)]

The problem is that all annotations must be repeated.
In a project of mine I have an annotation taking 5 parameters and would have to apply it twice, which would lead to constant copy-pasting after changes and overall code complication.

Is it possible to apply constructor annotations to the parameter as well? If not, is it possible to somehow shorten these special cases?

1 Like

You can use

@Target(AnnotationTarget.PROPERTY)
annotation class Annotation(val baz: Int)

to get rid of the need for specifing the use-site target, e.g. @property:Annotation.