@IntDef is one of my favourite annotations from the support annotations pack. Its main goal is to specify the possible values for a particular integer variable, but it can do much more than just that.

Not only it lets you easily change your enum to a bunch of ints (#perfmatters/#enummatters choose whichever you like more) and still be useful. Its interoperation with the Android Studio (versions >= 2.0) provides with a way to actually speed up your work. Especially if you’re the kind of person who likes his/hers switch statements.

Example 1:

Transforming an enum into a group of ints with @IntDef annotation:

(I currently use this @IntDef’s structure, but it’s not mandatory; you can organize that however you want)

Performance differences aside (if there actually are any), this may seem like a huge amount of code to write in comparison to a simple enum, but remember that those ints… really are ints. They do not have to be just some dummy values. You can use values that actually represent some sort of information (as long as they are unique from each other), including resource ids! And if you think of it that way and you try to compare an enum that stores this sort of data to an @IntDef structure, the difference is not that big anymore:

(alternatively you could also write a simple enum and create some sort of mapping function)

If you’re worried about the annoying process of writing @IntDef, check my other post where I explain how you can speed this up with the Multicursor feature.

Example 2:

If you have a bunch of int constants, that you don’t want to rewrite as an enum (like system constants) and you usually use them in switch statements, @IntDef can help you there. You can wrap them with an @IntDef interface once, and then reuse it in all switch statements in your code.

Here’s an example of that:

And then, whenever you write an OnTouchListener, just let Android Studio help you with creating your switch statement:

For me, the reusing of the @IntDefs got to a point, that is best describable by the quote from the Jake himself:

So here it is: IntDefs. Any contributions to it are more than welcome!

If you enjoyed this post, please show your support! Recommend, follow, comment. This means a lot!

senior android engineer @reddit | former android tech lead @getthefabulous | recovering feature creep 💉 | https://github.com/blipinsk

The (retired) Pub(lication) for Android & Tech, focused on Development