Location of type annotations

An oddity that I stumbled over in Kotlin programming for Android is the location of type annotations.

In Android, resources are generally referenced by Integer constants. There are many different types of resources, such as ids, layouts, drawables, colors, etc. To enable better IDE linting (I guess), it is possible to add an annotation to a(n Integer) type that should actually be a reference to a certain resource.
In Java, a function that creates a grey version of a given drawable might look like this:

Bitmap createGreyBitmap(@DrawableRes int id) { ... }

In Kotlin, the same looks like this:

fun createGreyBitmap(@DrawableRes id: Int): Bitmap { ... }

The issue I have with this, is that type annotations usually (always?) relate to the type, not the name of a variable / parameter / field. So, I would have expected it to look like

id: @DrawableRes Int

I wonder what is the reasoning behind requiring the annotation at the position it is right now?

Kotlin supports type annotations as well as parameter annotations. Which ones are applicable depends on how the annotation was defined.

Type annotations have been introduced in Java 8 only. Since Android does not generally fully support Java 8 yet, I’d assume that these Android ressource annotations are not type annotations but rather parameter annotations etc.

Just open the annotation’s definition. It will show you whether they are type annotations.

1 Like

Indeed, you are right, the @DrawableRes, @LayoutRes, @IdRes, @ColorRes etc. annotations are all defined as

@Target({METHOD, PARAMETER, FIELD, LOCAL_VARIABLE}) 

and not type annotations.

I tried it out, Kotlin type annotations are placed exactly where expected:

@Target(AnnotationTarget.TYPE) annotation class DrawableRes

fun createGreyBitmap(id: @DrawableRes Int): Bitmap { ... }

Cool stuff!

2 Likes