I decided to use the Groovy language for an Android app I was working on. Luckily it was fairly straightforward, but I noticed that the number of blogs and examples available to demonstrate using Groovy for Android development are far fewer than Java ones. Not only that, but many of them were out of date.
This is particularly true if you want to use libraries that are not straightforward coding, such as Dagger 2.
I was intending to write a simple proof-of-concept app to start with, to verify that I could use Dagger 2 and Groovy together. Then I found this example app on Github.
However this simple Dagger 2 example did now show how to use the @Inject annotation (which is my preferred way to do Dependency Injection into activities), so I created a fork that did.
Note that you will need to use an up-to-date version of Groovy (2.4.x) to get Groovy and Dagger 2 working on Android.
I only had to make a few code changes to use @Inject, you can check the commits in the project to see what they were.
Firstly in the component interface (in the example, it is called demo.simplegroovyapp.component.VehicleComponent), I added a statement that would inject the dependency objects into the activity.
void inject(MainActivity mainActivity)
Then in the activity class (demo.simplegroovyapp.MainActivity) add the @Inject annotation to the field that was to be injected. The other important change I made was to add the public access modifier, I’ll explain later why this is necessary.
In other words, from this:
@Inject public Vehicle vehicle
In the onCreate() method, this line was added to inject the dependencies into the activity.
I also commented out the statement that was previously used to manually retrieve the Vehicle object, as it was no longer necessary.
//vehicle = vehicleComponent.provideVehicle()
Property or Field?
In Groovy it is quite common to see data in a class being defined without an access modifier (public, protected, private).
Likewise in many Dagger 2 Java examples I’ve seen, the @Inject annotation is used on fields without the access modifier.
@Inject MyPresenter mypresenter;
However when this is done in Groovy, you are specifying a property, not a field.
Hence Dagger can’t inject the Vehicle object into the activity, even with the @Inject annotation. Once the public access modifier is added, then Dagger works as expected.