Annotation Processing


#1

Hello, guys!

I’ve just stumbled upon a small example project https://github.com/damianpetla/kotlin-dagger-example, which shows a working example of annotation processing in Kotlin!
But I still can’t find the answer, why does it work? The generated code is valid. Other libraries use the same tecnique, but it seems, they don’t even dive into Kotlin code.
But Dagger 2 works. How?
I’d really want to write some codegeneration tools


#2

I think the answer is likely this (from ReadMe.md):

  1. Classes and interfaces that Dagger use for generating implementations must be kept in Java. If it's moved to Kotlin it won't be generated e.g. AndroidModule, ApplicationComponent

#3

I've read it, surely. But it doesn't answer for me. Dagger has access to `Inject` annotation on a setter in Kotlin code and generates appropriate construction for it. I assume, that it has access to enclosing element as well. So, annotation processor has access to Kotlin elements?


#4

That's a little bit strange, and we need to debug the code and see how setter for the property get called. I quickly looked at docs and there are few things that may explain it: * Dagger 1.0 is said to be "half static, half reflection" injection framework. * Dagger 2.0 is said to be "in transition from Dagger 1.0 to fully static solution"

So, probably, it’s “half reflection” that gets it running, and probably it will stop working in Dagger 2.0 some day, because clearly it cannot read Kotlin’s source code, as Kotlin’s compiler doesn’t run any annotation processing tools.


#5

Could it be that the Inject annotation is kept and then processed later in the Java pass ?

Maybee they…
build all their machinery, their DAG graph, they attach their modules to their Graph in the Java pass

retain the Inject annotation set on the Kotlin side and only use the kotlin constructor on the Kotlin pass


#6

What I'm talking is about Dagger 2, actually. There are no reflection, and if we have code   var locationManager: LocationManager? = null   [Inject] set the generated would be   `instance.setLocationManager(arg0Provider.get());`

If we annotate delegated property, Dagger 2 will show error message about ReadOnlyProperty<*> provider. SO, it looks like it has full access to code model and detects annotations in Kotlin.

May be Olivier’s anwer is a key, but I didn’t catch that :smile: And how can it be used to make fully working annotation processor.