Processing annotations on expressions

Unlike Java, Kotlin allows me to use an annotation on an expression, e.g.:

    @Retention(AnnotationRetention.SOURCE)
    @Target(AnnotationTarget.EXPRESSION)
    annotation class Example

    class Worker {
        fun work() {
            var a = 0
            @Example
            a += 1
        }
    }

I have been looking for some time, but can’t work out how to identify the annotation site during annotation processing (with kapt).

Using:

roundEnv.getElementsAnnotatedWith(Example::class.java)

Gives no results, which makes sense as there are no suitable element kinds in Java.

I’ve also seen notes that state that annotations with an EXPRESSION target are unavailable at runtime which again makes sense. But if this is true, then I assume there must be some way to access the annotations at compile time or they’re a bit pointless. What am I missing??

If it helps I simply want to count the uses of an annotation within a specific method and retrieve the attributes from the annotations in the order that they are declared. The method will have a different annotation, so a potentially suitable pattern might be to identify the method element using the round environment and then get a list of all the annotation instances (of my expression annotation) within that element – I just can’t see how to do that.

You can’t use annotation processing. The only way to do that (that I’m aware of) is using a compiler plugin. The problem with that is that compiler plugins currently don’t have a stable (or documented) API. My guess is that an experimental API will implemented during 1.4.x or possibly 1.5. There is a 2018 Kotlin Conf talk about writing your own plugin with the current API if you are interested however there are no guarantees that this API will not change at any time. I also wouldn’t be surprised if this changes with 1.4-1.5 because of the compiler rewrite which is currently happening.