前言
谷歌官方建议:Android项目中应避免使用枚举
单个枚举会使应用的 classes.dex 文件增加大约 1.0 到 1.4 KB 的大小。这些增加的大小会快速累积,产生复杂的系统或共享库。如果可能,请考虑使用 @IntDef 注释和 ProGuard 移除枚举并将它们转换为整数。此类型转换可保留枚举的各种安全优势。
使用@IntDef annotation需要引入
compile 'com.android.support:support-annotations:28.0.0'
@IntDef annotation在Java文件中使用
//使用枚举
public enum Color{
RED, BLUE, YELLOW, GREEN, PURPLE, WHITE, BLACK
}
//使用@IntDef annotation实现与枚举相似的功能
public static final int RED = 0;
public static final int BLUE = 1;
public static final int YELLOW = 2;
public static final int GREEN = 3;
public static final int PURPLE = 4;
public static final int WHITE = 5;
public static final int BLACK = 6;
@IntDef({RED, BLUE, YELLOW, GREEN, PURPLE, WHITE, BLACK})
@Retention(RetentionPolicy.SOURCE)
public @interface Color{};
void setColor(@Color int COLOR){
color = COLOR;
}
在调用此函数的时候,参数名称如果不是IntDef中的变量名称的时候,例如setColor(2),Android Studio中就会提示错误(虽然编译仍然会通过)。
@IntDef annotation在Kotlin文件中使用
把以上代码转换成Kotlin代码,不过很遗憾,并没有起到编译时类型检查的功能。
As of Kotlin 1.0.3, the @IntDef annotation is not supported, but support is planned for later versions. The Kotlin way of making these compile time checks is to use an enum class instead of a series of Int constants.
Kotlin1.0.3以后已经不支持@IntDef annotation了
结论
kotlin文件中不支持@IntDef annotation,以后版本可能会支持。