Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

android
enum
intdefs
java
communitycreator

Enums and @IntDef in Android

Ansh Sachdeva

Enums

Enumerations (also known as enums) serve the purpose of representing a group of named constants in a programming language.
We often use enums to make a cool, restricted group of values that a function or statement could take.
However, enums are usually considered bad practice in Android because they often require more than twice as much memory as static constants.

Enter IntDef

@IntDef is a way of replacing an integer enum where there’s a parameter that should only accept explicit int values. We can use IntDef to ensure that the value is one of the expected values by adding an annotation. For example:


public class example {
   @IntDef( {Type.TYPE_MUSIC,Type.TYPE_PHOTO,Type.TYPE_TEXT})
    public  @interface  Type{
        int TYPE_MUSIC = 0;
        int TYPE_PHOTO = 21;
        int TYPE_TEXT = 42;
    }

  // Mark the argument as restricted to these enumerated types
  public void getItemType(@Type int itemType) {
    int res = itemType;
  }
}

The function will allow users to pass any integer value, but it will give a lint warning if the value is not Type.TYPE_MUSIC,Type.TYPE_PHOTOorType.TYPE_TEXT(yes, even if 0, 21, or 42 are passed directly).

RELATED TAGS

android
enum
intdefs
java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring