Specifying a use-site target

Let's look at how specifying different use-site targets impacts the generated Java code. We'll start by defining a simple ViewModel class:

class ViewModel( @param:ColorRes val resId:Int )

In this code snippet, we've added a @ColorRes annotation with a use-site of param. By adding this, the ColorRes annotation will be applied to the constructor parameter in the generated Java class:

public final class ViewModel {
private final int resId;

public final int getResId() {
return this.resId;
}

public ViewModel(@ColorRes int resId) {
this.resId = resId;
}
}
The @ColorRes annotation is an annotation from the Android support library. It can be used to specify that an integer value represents a resource identifier.

Next, we'll change the use-site to field:

class ViewModel( @field:ColorRes val resId:Int )

Now, we can see that the ColorRes annotation is then applied to the resId field of the generated ViewModel class:

public final class ViewModel {
@ColorRes
private final int resId;


public final int getResId() {
return this.resId;
}

public ViewModel(int resId) {
this.resId = resId;
}
}

We can use the get target to add the annotation to the generated getter:

class ViewModel( @get:ColorRes val resId:Int )

Once we do that, we can see that the Java getter now has the ColorRes annotation:

public final class ViewModel {
private final int resId;

@ColorRes
public final int getResId() {

return this.resId;
}

public ViewModel(int resId) {
this.resId = resId;
}
}

We can also specify multiple use-site targets if we want to add the annotation to multiple generated elements:

class ViewModel( @get:ColorRes @param:ColorRes val resId:Int )

In this case, the getter and the constructor parameter will both have the ColorRes annotation applied to them in the generated code:

public final class ViewModel {
private final int resId;

@ColorRes
public final int getResId() {

return this.resId;
}

public ViewModel(@ColorRes int resId) {
this.resId = resId;
}
}

By specifying use-site targets, we can ensure that our annotated parameters and properties are annotated as expected and work correctly across both Kotlin and Java.